Next page | Contents page |

Lists, iterators, generics, for-each loops

Lists

java.util.List is an interface. java.util.ArrayList is an implementation of it. Very useful - like an array which expands and contracts as objects are added or removed. Can hold any objects so need to cast when getting references to objects in the list. Eg,

	List partsList = new ArrayList ();
	// NB: Best practice: declare variables as interface type whenever possible
	...
	partsList.add (part);
	...
	for (int i = 0; i < partsList.size(); i++)
	{
		Part p = (Part) partsList.get(i); // Cast
		// ... work with the part
	}

NB: In early versions of Java there was java.util.Vector which is very similar to ArrayList. It is still in the API and you will see it used in a lot of code. Do use ArrayList instead.

Iterators

There is another way to go through all elements in a List (more generally, through any java.util.Collection):

	for (java.util.Iterator it = partsList.iterator (); it.hasNext ();  )
	{
		Part p = (Part) it.next ();
		// ... work with the part
	} 

NB: In early versions of Java there was java.util.Enumeration which is very similar to Iterator. It is still in the API and you will see it used in a lot of code. Do use Iterator instead - or, since Java 5, for-each loops (below).

All of the above is what you would have written before Java 5 but now best practice is to say what type of objects the list will hold, using some new syntax called "generics".

Generics

Often we want to be able to specify what kind of objects a List (more generally java.util.Collection) holds, and would like not to have to cast a retrieved Object to the real type (and risk throwing ClassCastExceptions if we don't check type before the cast). Completely new syntax in Java 5 enables this:

	List<String> a = new ArrayList<String> ();
	a.add ("Some text");
	String s = a.get (0);   // No cast needed.

Always read "<X>" as "of type X". Above we have an ArrayList of type String. It can only hold Strings and the compiler will prevent you adding any other type of object to it.

For-each loops

Java 5 also added new syntax to avoid the need to use java.util.Iterators:

	List<String> a = new ArrayList<String> ();
	a.add ("Some text");
	...
	a.add ("Some other text");

	for (String s : a)
	// Read as "for each String s in a"
	{
		doSomething (s);
	}

This reduces risk of errors, particularly for nested iterations.

For-each loops can be used with arrays too: you no longer have to remember about the length field.

Next page | Contents page |