College Board Unit 4
How it works
An ArrayList grows and shrinks at runtime, unlike a fixed-size array. It reports its size through size(), reads with get(i), replaces with set(i, value), and appends with add(value). The type parameter must be a class type, so an ArrayList of integers is declared as ArrayList<Integer> rather than ArrayList<int>. Valid indexes still run from 0 through size() - 1.
Use size() for bounds and get() for access, keeping in mind both change as the list is modified.
Common error
Using length or length() on an ArrayList, or an index equal to size().
Worked example
Java
ArrayList<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Grace");
names.set(0, "Lin");
System.out.println(names.get(0) + ":" + names.size());Output
Lin:2set replaces index 0 without increasing the list size.
Exercises
6.1.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3); list.add(7);
System.out.println(list.set(1, 9));
System.out.println(list);Show solution
Output
7
[3, 9]set returns the old element and leaves the size unchanged.
6.1.2 · Write code
Build an ArrayList<String> containing "red", "green", and "blue". Replace "green" with "gold" and print the resulting list.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
ArrayList<String> colors = new ArrayList<String>();
colors.add("red"); colors.add("green"); colors.add("blue");
colors.set(1, "gold");
System.out.println(colors);