My Photo
Name:
Location: Bloomington, Indiana, United States

Saturday, February 28, 2009

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.


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");
}

3 Comments:

Blogger Unknown said...

best franchise opportunities

Promotional Stress ballsThis blog does not allow anonymous comments.

9:59 PM  
Blogger Unknown said...

USB promo

web designrence consists of the words "and that night, they were not divided", a British court judged it obscene because it defended "unnatural practices between women". In the United States the book survived legal chall

7:19 PM  
Blogger luckys said...

ilovetyping 

8:10 AM  

Post a Comment

<< Home