Java's Generic For Loop
Jakob Jenkov |
Java's Generic's has a new for loop. This new for loop is also sometimes referred to as
the "for each" loop. This new for loop makes it easier
to iterate generic collections. For instance, iterating generic Set's
or List's
.
Here is a simple example that iterates a generic List
:
List<String> list = new ArrayList<String>; for(String aString : list) { System.out.println(aString); }
Notice how a String
variable is declared inside the parantheses of
the for-loop. For each iteration (each element in the List
) this
variable contains the current element (current String).
Here is an example that uses a Set
:
Set<String> set = new HashSet<String>; for(String aString : set) { System.out.println(aString); }
Notice how the for-loop looks the same as for a List
.
Here is an example for a Map
Map<Integer, String> map = new HashMap<Integer, String>; //... add key, value pairs to the Map for(Integer aKey : map.keySet()) { String aValue = map.get(aKey); System.out.println("" + aKey + ":" + aValue); } for(String aValue : map.values()) { System.out.println(aValue); }
Notice how an Integer
and a String
variable is declared inside the parantheses of
each for-loop. For each iteration (each element in the Map
's key set or value collection) this
variable contains the current element (current Integer or String).
Tweet | |
Jakob Jenkov |