Task 3 of 11 · 0 solved · 11 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.3 Lists — access and traversal

Lesson

Reading items and looping

Read the item at a position with get(i) — indices start at 0, just like arrays. To visit every item, loop i from 0 up to less than size(). Note the method-call style: list.get(i) and list.size(), not list[i] or list.length.


Worked example

ArrayList<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Sam");
names.add("Bo");
for (int i = 0; i < names.size(); i++) {
    System.out.println(names.get(i));
}

Prints Ada, Sam, Bo on three lines.


▶ Try it: run this to print each item. Add or change names and re-run — the loop uses size(), so it always fits.



How do you read the element at index i of a list?


Which gives the number of items in a list?


Type exactly what this program prints.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> items = new ArrayList<String>();
        items.add("pen");
        items.add("cup");
        for (int i = 0; i < items.size(); i++) {
            System.out.println(items.get(i));
        }
    }
}

True or false?