Jenkov.com
Tutorials Books About
Java Generics

1 Java Generics Tutorial
2 Generic List in Java
3 Generic Set in Java
4 Generic Map in Java
5 Generic Classes in Java
6 Java Generic Methods
7 Java Generics - Class Objects as Type Literals
8 Java's Generic For Loop
9 Java Generics - Implementing the Iterable Interface
10 Java Generic's Wildcards




Java's Generic For Loop


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).



Connect with me: Newsletter - Get all my free tips!