Iterating Over an ArrayList – Collections, Part I: ArrayList

12.5 Iterating Over an ArrayList<E>

Various methods for iterating over collections are discussed in §15.2, p. 791. Here we look at a very common task of iterating over a list to perform some operation on each element of the list.

We can use positional access to iterate over a list with the for(;;) loop. The generic method printListWithIndex() in Example 12.1 uses the for(;;) loop to create a new ArrayList of String that contains each element of the argument list prefixed with the index of the element.

Click here to view code image

public static <E> void printListWithIndex(List<E> list) {
  List<String> newList = new ArrayList<>();
  for (int i = 0; i < list.size(); i++) {
    newList.add(i + “:” + list.get(i));
  }
  System.out.println(newList);
}

Sample output from the method call printListWithIndex(strList) is shown here:

Click here to view code image

[0:level, 1:Ada, 2:kayak, 3:Bob, 4:Rotator, 5:Bob]

The method printListWithIndex() in Example 12.1 can print any list in this format. Its header declaration says that it accepts a list of element type E. The element type E is determined from the method call. In the preceding example, E is determined to be String, as a List of String is passed in the method call.

Since the ArrayList<E> class implements the Iterable<E> interface (i.e., the class provides an iterator), we can use the for(:) loop to iterate over a list.

for (String str : strList) {
  System.out.print(str + ” “);
}

The ArrayList<E> also provides specialized iterators to iterate over a list (§15.3, p. 801).

For performing a given action on each element of a list, the forEach() method can be used (§15.2, p. 796), where the action is specified by a consumer (§13.7, p. 709).

One pertinent question to ask is how to remove elements from the list when iterating over the list. The for(:) loop does not allow the list structure to be modified:

Click here to view code image

for (String str : strList) {
  if (str.length() <= 3) {
    strList.remove(str);               // Throws ConcurrentModificationException
  }
}

We can use positional access in a loop to iterate over the list, but we must be careful in updating the loop variable, as the list contracts when an element is removed. Better solutions for this purpose are discussed in §15.2, p. 796.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *