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.
get(i)
i
size()
list.get(i)
list.size()
list[i]
list.length
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.
Ada
Sam
Bo
▶ 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?