Skip to the content.
Home 7.1 Introduction 7.2 Methods 7.3 Traversing 7.4 Algorithms 7.5 Searching 7.6 Sorting 7.7 Ethical Issues

7.3 - Traversing Arraylists

ArrayLists Lesson

AP CSA

  • IndexOutOfBoundsException
  • While Loops
  • 7.3 Traversing Arraylists

    You can traverse through the elements in an ArrayList using loops. In order to traverse ArrayLists, we can use iterative statements, or loops. We can use For Each Loops, For Loops, and While Loops

    The following code uses a For Each loop to traverse through the ArrayList.

    //7.3.1: For Each Loop
    ArrayList<Integer> myList = new ArrayList<Integer>();
            myList.add(50);
            myList.add(30);
            myList.add(20);
            for (Integer value : myList)
            {
                System.out.println(value);
            }
    
    50
    30
    20
    

    Popcorn Hack #1:

    Modify the code above so that it prints out the sum of all the elements in the list.

    //7.3.1: For Each Loop
    ArrayList<Integer> myList = new ArrayList<Integer>();
            myList.add(50);
            myList.add(30);
            myList.add(20);
            int sum = 0;
            for (Integer value : myList)
            {
                sum += value;
                System.out.println(sum);
            }
    
    50
    80
    100
    

    The problem with For Each loops is that you can’t modify the ArrayList. To do that, you will need to use another type of loop. If you attempt to modify the ArrayList, you will get a ConcurrentModificationException error.

    ConcurrentModificationException Error:

    • Happens when you try to modify the structure of an ArrayList using a For Each loop.

    Think about it this way: Imagine you are standing in a line at the store and then somebody cuts the line. The order of the line has changed. The store doesn’t want people cutting the line becaues it changes the order and creates confusion. So, it throws out a ConcurrentModificationError to alert you that something is wrong and that you shouldn’t do it.

    It’s the same for For Each Loops in Java - You can’t add or remove elements because it changes the structure of the loop.

    image

    Common mistakes with For Each Loops:

    1. Make sure that the data type of your variable is the same as the data type of the ArrayList
    2. Don’t try to modify the ArrayList!!!!!! I can’t stress this enough

    image

    For Loops

    Here’s how to traverse through an arraylist using a For Loop. The following code will give you an IndexOutOfBounds error, do you know how to fix this error?

    There are three major parts of a for loop:

    • Initialisation, this is where you declare the variable index

    • Boolean condition, this is where you declare the stop condition, when it’s true, it stops.

    • Update, this is the increment value, i++ is increment and i– is decrement

    // 7.3.2 For Loops
    ArrayList<Integer> myList = new ArrayList<Integer>();
            myList.add(50);
            myList.add(30);
            myList.add(20);
            for (int i = 0; i <= myList.size(); i++)  
            {
                System.out.println(myList.get(i));
            }
    
    
    50
    30
    20
    
    
    
    ---------------------------------------------------------------------------
    
    java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
    
    	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    
    	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    
    	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
    
    	at java.base/java.util.Objects.checkIndex(Objects.java:359)
    
    	at java.base/java.util.ArrayList.get(ArrayList.java:427)
    
    	at .(#32:1)
    

    IndexOutOfBoundsException

    • This happens when the program is trying to fetch something that isn’t there. If we have the equals since in the for loop, it will try to fetch up to index 3 because thats the list size. When we remove the equals sign, it goes to whatever is <3, which is 2. So, it fetches up to index 2, meaning 3 elements.

    Popcorn Hack 2:

    Suppose we have an arraylist named grades, and we want to remove the entries that are lower than 70. Use a for loop to achieve this.

    image

    import java.util.ArrayList;
    import java.util.List;
    
    ArrayList<Double> grades = new ArrayList<>();
    grades.add(68.9);
    grades.add(71.0);
    grades.add(100.0);
    grades.add(80.0);
    for(int i = grades.size() - 1; i >= 0; i--) {
        if(grades.get(i)<70){
            //remember, use grades.remove(index) 
            grades.remove(i);
        }
    }
    System.out.println(grades);
    
    [71.0, 100.0, 80.0]
    

    While Loops

    Here is the final example of traversing through ArrayLists using while loops

    ArrayList<String> fruits = new ArrayList<>();
    fruits.add("apple");
    fruits.add("banana");
    fruits.add("orange");
    
    int index = 0;
    while (index < fruits.size()) {
        System.out.println(fruits.get(index));
        index++;
    }
    
    apple
    banana
    orange