Using collections in Java: enumerating items in a list

On the previous page, we began our tour of Java collections by looking at creating and using an ArrayList. We saw an example of how to add an item to the list, query the list's size (number of elements currently in the list) and fetch the nthe element.

Another commonly needed operation is to enumerate or iterate through all of the items in the list. Now, one way we could do this would be with a plain old for loop: query the number of elements in the list, and then cycle through from 0 to that number minus one, pulling out the nth element on each cycle through the loop:

List<String> myList = ...

for (int len = myList.size(), i = 0; i < len; i++) {
  String s = myList.get(i);
  System.out.println("Item " + i + " is " + s);

Note that rather than calling the size() method on every pass through the loop, we can read the size once and store it in a local variable. If anything, this is more of a programming idiom than a real performance gain: the overhead of calling size() isn't much for most collections, especially with modern JVMs that can inline the call.

A disadvantage of the method we just mentioned is that it assumes that for a particular list, the cost of finding the nth element is negligible. That's the case for an ArrayList, but not for a LinkedList, which has to 'cycle through the chain' to find the object at a given "index". From Java 5 onwards, the compiler can help us out by allowing us to use a special loop syntax:

for (String s : myList) {
  System.out.println("Next item: " + s);

The above code will create a loop that cycles through all the elements in the list, and on each cycle assigns the next element in the list to the variable s. Under the hood, the compiler will generate code that iterates through the list by effectively asking the list which iteration method to use.

A bit later, we'll look at how the compiler generates more efficient code.

Next: using sets

On the next page, we look at sets, which are used to test whether an item is "present or not" in the collection, but without allowing duplicates and generally without keeping items in a fixed order, unlike lists.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.