Please enable JavaScript to use CodeHS

Chapter 7

ArrayLists

7.3 Traversing ArrayLists

As covered in Unit 6, traversing is the process of moving through all the items in an array or data structure. Loops can be used to traverse arrays by using the incremental variable to access each individual element in an array:

int[] scores = {80, 92, 91, 68, 88};
for(int i = 0; i < scores.length; i++) 
{ 
    // This prints out the ith element! 
    System.out.println(scores[i]);
 }
Java

Basic ArrayList Traversals

The same process is applicable to traversing elements in an ArrayList:

ArrayList<Integer> scores = new ArrayList<Integer>();

for(int i = 0; i < scores.size(); i++)
{
    // This prints out the ith element!
    System.out.println(scores.get(i));
}
Java

The primary difference between array and ArrayList traversal lies in the methods used to access each element. For ArrayLists, size is used to determine the number of iterations of the increment variable, and get is used to access the element at a given index. This same difference applies to ArrayList while loop traversals and enhanced for loops:

// while loop traversal
int i = 0;
while(i < scores.size())
{
    System.out.println(scores.get(i));
    i++;
}

// Enhanced for loop traversal
for(int score: scores)
{
    System.out.println(score);
}
Java

Removing Elements During Traversal

Because ArrayLists can change size, it’s necessary to take caution when traversing them, as the changing size of the ArrayList can affect which elements are being accessed.

Consider the following list, and associated method:

list

0 1 2 3 4
“I” “am” “Andrew” “Aardvark” “Jr.”
//Removes all Strings from an ArrayList that begin with the letter 'A'
public void removeA(ArrayList<String> list)
{
  for(int i = 0; i < list.size(); i++)
  {
    if (list.get(i).startsWith("A"))
    {
      list.remove(i);
    }
  }
}
Java

This method intends to remove each element in a list that starts with the letter A. The implementation of this however, has unintended consequences. When i = 2, the conditional if statement will remove the item at index 2 from the list. It then will return to the for loop header, and increment the value of i to i = 3.

When remove is used on this list, each value in the list after index 2 shifts one space down in the ArrayList:

list

0 1 2 3
“I” “am” “Aardvark” “Jr.”

However, the value of i in the for loop header is now 3. When the conditional statement checks for a word that starts with “A” at index 3, there is none. The value “Aardvark” unintentionally stays in the list, even though the method was designed to remove all instances of words that start with “A”.

The solution to this problem is adding a decrement after the list item is removed:

//Removes all Strings from an ArrayList that begin with the letter 'A'

public void removeA(ArrayList<String> list)
{
  for(int i = 0; i < list.size(); i++)
  {
    if (list.get(i).startsWith("A"))
    {
       list.remove(i);
       i --; //decrease the value of i by one!
    }
  }
}
Java

Now when the list item is removed at index 2, the value of i is decreased to 1. When the for loop iterates again, the value of i will increase from 1 to 2 again, allowing the program to check the new value at index 2 after the elements shift position.

Common Traversal Errors

When using these traversal methods, there are several common Exceptions that may occur if the traversal is implemented incorrectly:

  1. IndexOutOfBounds Exception:

    When iterating through an ArrayList, it’s common that the iteration includes an index that is outside of the current index range. For example, if the for loop conditional statement occurs from i = 0 to i <= list.size(), then the iteration will include one extra iteration that searches for an index at position list.get(list.size()), even though ArrayList indices only range from 0 - list.size() - 1. Accessing an index that is not within the range of the existing ArrayList will result in an IndexOutOfBounds Exception, commonly known as an “off by one” error.

  2. ConcurrentModification Exception

    This exception occurs when attempting to remove an item from an ArrayList during an enhanced for loop. This error occurs when objects are being modified while they are being iterated on, which is what happens when enhanced loops are used on ArrayLists. Generally speaking, removing and adding items from an ArrayList should not be done while using enhanced for loops.

Reading List

While Loop ArrayList Traversal

ArrayList Traversing Error

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    What is the standard method used to traverse an ArrayLists?

Exercise: Traversing Odds

Create a method removeEvens that removes all even elements from an ArrayList of Integers. The method should also print all the remaining items in the ArrayList.

Once the method is created, call it on the existing ArrayList in the main method.