I have created sample program to demonstrate Java for-each loop syntax, using both a List with pre-Java5 syntax, and a second example using Java Generics
import java.util.ArrayList;
import java.util.List;
public class JavaForLoop
{
public static void main(String[] args) {
withoutGenerics();
withGenerics();
}
private static void withoutGenerics() {
List integers = new ArrayList();
integers.add(new Integer(10));
integers.add(new Integer(20));
integers.add(new Integer(30));
// you get an Object back from a List
for (Object integer : integers)
{
// to convert from an Object to an Integer
System.out.println(integer.toString());
}
}
/*In this example method when you get the items out of the list you get them out as Objects, which you must then cast to the correct type.*/
private static void withGenerics() {
List integers = new ArrayList();
integers.add(new Integer(40));
integers.add(new Integer(50));
integers.add(new Integer(60));
// you get an Object back from a List
for (Integer integer : integers)
{
// here you know for sure that you're dealing with
// an Integer reference
System.out.println(integer);
}
}
}
/*In this method, I have specify the type of the collection when you created it. In this cast the extra casting step is not required*/
No comments:
Post a Comment