|
|
Using collections in Java: enumerating items in a listOn 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
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
A bit later, we'll look at how the compiler generates more efficient code. Next: using setsOn 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.
Written by Neil Coffey. Copyright © Javamex UK 2011. All rights reserved. If you have any feedback on the Java collections tutorials in this section or about the content of this site in general, please leave a message on the Javamex forum. |