Generic Collections

Problem

The Java Collections Framework provides several different types of collection classes

ArrayList

LinkedList

HashSet

TreeSet

Hashtable

Stack

etc.

In earlier versions these were collections of objects. This made explicit casting necessary and circumvented the type checker:

ArrayList document = new ArrayList();
document.add("The");
document.add("End");
document.add(new Integer(42)); // oops, didn't mean to do this

Iterator p = document.iterator();
while(p.hasNext()) {
   String word = (String)p.next(); // cast needed
   System.out.println(word);
}

Solution

In more recent versions of Java the collection classes are generic collections (i.e., parameterized by the type of data they contain:

ArrayList<String> document = new ArrayList<String>();
document.add("The");
document.add("End");
document.add(new Integer(42)); // type checker won't allow this

Iterator<String> p = document.iterator();
while(p.hasNext()) {
   String word = p.next(); // no cast needed
   System.out.println(word);
}

Newer versions of Java also provide the enhanced for-loop:

for(String word: document) {
   System.out.println(word);
}

References

The Java Collections Framework