ArrayList
- Create an `ArrayList` and use `add`, `get`, `size`, and `remove`
- Explain how `remove(index)` shifts the remaining elements
- Predict results of retrieving elements after modifying the list
A resizable list
An ArrayList<E> is a resizable list of objects, where E is the element type. Unlike an array, it grows and shrinks as you add and remove. Create one with ArrayList<String> list = new ArrayList<String>();. Because elements must be objects, use wrapper types for primitives: ArrayList<Integer> for whole numbers, not ArrayList<int>.
The core methods
The everyday methods are add(x) to append to the end, get(i) to read the element at index i, size() to count elements (a method, with parentheses), and remove(i) to delete the element at index i. Indices are zero-based, just like arrays, and size() returns the current number of elements.
remove shifts everything after it
When you remove(i), every element after index i shifts left to fill the gap, and the size drops by one. If a list is [5, 8, 2] and you call remove(1), the 8 is deleted and the list becomes [5, 2] — the former index 2 (2) is now at index 1. This shifting is a frequent source of bugs when removing inside a loop.
Trace this code: ArrayList<Integer> list = new ArrayList<Integer>(); then list.add(5); list.add(8); list.add(2); then list.remove(1); then System.out.println(list.get(1));
- 1.After the three adds, the list is [5, 8, 2] at indices 0, 1, 2.
- 2.
remove(1)deletes the element at index 1 (the 8), and the 2 shifts left. - 3.The list is now [5, 2]: index 0 = 5, index 1 = 2.
- 4.
get(1)reads index 1, which is now 2.
2. Removing index 1 (the 8) shifts the 2 into index 1.What does this print? `ArrayList<String> list = new ArrayList<String>();` then `list.add("a"); list.add("b"); list.add("c");` then `System.out.println(list.size());`
Use size() (a method, with parentheses) for an ArrayList, but length (a field, no parentheses) for an array. They are not interchangeable.
What does this print? `ArrayList<Integer> list = new ArrayList<Integer>();` then `list.add(5); list.add(8); list.add(2);` then `list.remove(1);` then `System.out.println(list.get(1));`
When removing elements in a loop, remember each remove(i) shifts later elements left. Iterating forward with a normal index can skip elements — a very common FRQ trap.
Answer the 2 checkpoints as you read.
Sign in to save your progress