This code uses java 5's(jdk1.5.0) new feature called generics. They are supposed to increase type safety by only allowing the <type> or it's subtypes to be stored within the Collection. Also casting should not be needed when grabbing an element out of a collection to be stored in ref variable of the <type>. But for some reason a cast is still needed ie. Integer integer = (Integer)i.next(); even though the Collection is specified only to hold <Integer> types. If <type> is added to the Iterator then the cast is not needed.
Code:
for(Iterator<Integer> i = list.iterator();i.hasNext();){
Integer integer = i.next(); then the cast is not needed.
}
Code:
import java.util.*;
List<Integer> list = new ArrayList<Integer>();
int element = 0;
while(true){
list.add(new Integer(element));
element = element + 1; // add 4 elements
if(element == 4) break;
}
for(Iterator i = list.iterator();i.hasNext();){
Integer integer = (Integer)i.next();
System.out.println(integer);
}