Java method level generics - Getting First Element from an Iterator.
There are ample examples where you are given an iterator but you are only interested in the first element of the collection. Following through some code i had to read, which was doing WSDL parsing, I ran into some code which most probably annoyed the programmer because of the repeating code of the same form that had to be written for different Iterator types, to loop through the iterator and extract the first element. One solution, besides writing helper for each case is to not do typing at all and do non generic helper method.
Obviously this is not why i wrote this blog. I wrote down the following code which is type safe and gives exactly what i want. This makes use of java method level templates. This is type safe because when some one calls this method the templates will be instantiated and the return values are obviously typed based on the instantiation happened at the caller and no type casting necessary.
There are ample examples where you are given an iterator but you are only interested in the first element of the collection. Following through some code i had to read, which was doing WSDL parsing, I ran into some code which most probably annoyed the programmer because of the repeating code of the same form that had to be written for different Iterator types, to loop through the iterator and extract the first element. One solution, besides writing helper for each case is to not do typing at all and do non generic helper method.
public static Object getFirst(Iterable itr){
for (Object object : itr) {
return object;
}
throw new RuntimeException("Iterator empty");
}
Obviously this is not why i wrote this blog. I wrote down the following code which is type safe and gives exactly what i want. This makes use of java method level templates. This is type safe because when some one calls this method the templates will be instantiated and the return values are obviously typed based on the instantiation happened at the caller and no type casting necessary.
public static <T extends Object> T getfirst(Iterable<T> vals) {
for (T val: vals) {
return val;
}
throw new RuntimeException("Iterator empty");
}