Java Generics
Java Generics Introduction
Generic List
Generic Set
Generic Map
Generic Classes
Generic Methods
Class Objects as Type Literals
Generic For-Loop
Implementing the Iterable Interface
Generic Wildcards
 


Java's Generic For Loop

Connect with me:  
  Jenkov.com - News

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


NextNext : Implementing the Iterable Interface

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