Looping through a Collection object

This example shows how to iterate through an object which implements the Collection interface. Here we use and ArrayList but the same code can roughly be applied to other classes that implements the Collection interface since they’ll also implement the Iterable interface.
In the example code we use three different ways that do exactly the same thing, namely to loop through the elements of the list and print them out.

First we create the ArrayList using generics which means that we specify of what type the elements of the list should be. In this case we specify that the elements should be of type String.
In the first two iteration examples we call the iterator() method to get the reference to the objects iterator. Once obtained, we can loop for as long as its hasNext() method returns true.
The last iteration example shows the relatively new way to loop, introduced in Java 5. Basically we declare a variable called element and say that for each element in the array, assign its value to the variable element.

Naturally, the output of the code is:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?