AP Computer Science A · Data collections
ArrayLists
1Creating an ArrayList
An ArrayList is a resizable list of objects, from java.util:
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> nums = new ArrayList<Integer>();
- Holds only reference types; for numbers use the wrapper classes
IntegerandDouble. - Java converts automatically between
intandInteger(autoboxing and unboxing). - Size changes as elements are added and removed.
Check yourself
Which declaration is valid?
Show the answer
ArrayList<Integer> list = new ArrayList<Integer>();
Wrapper class needed.
2ArrayList methods
From the Java Quick Reference:
size(): number of elements.add(obj): appends to the end; returns true.add(index, obj): inserts atindex, shifting later elements right.get(index): returns the element.set(index, obj): replaces the element and returns the old one.remove(index): removes the element, shifting later elements left, and returns it.
Worked example:
list.add("A"); list.add("B"); list.add("C");→ [A, B, C]list.add(1, "X");→ [A, X, B, C]list.set(2, "Y");→ [A, X, Y, C] (returns "B")list.remove(0);→ [X, Y, C]
add and remove shift later elements; set replaces one in place
Check yourself
After list = [5, 8, 2], list.add(0, 1) gives:
Show the answer
[1, 5, 8, 2]
Inserts at index 0.
3Traversing and removing
Traverse with an indexed loop (i < list.size()) or a for-each loop.
Removing while traversing needs care. Removing at index i shifts the next element into position i, so a forward loop that always does i++ skips it. Solutions:
- Loop backwards:
for (int i = list.size() - 1; i >= 0; i--). - Or only increment
iwhen nothing is removed.
Never add or remove inside a for-each loop over the same list: it throws ConcurrentModificationException.
remove all negatives from [3, −1, −4, 2].
- Forward loop with
i++always: removes −1 at index 1, −4 shifts to index 1, thenibecomes 2 and −4 is skipped. - Backward loop: checks 2, −4 (remove), −1 (remove), 3 → [3, 2]. Correct.
Check yourself
Why loop backwards when removing elements from an ArrayList?
Show the answer
Removing does not shift the elements still to be checked
Shifts affect only checked indices.
4ArrayLists versus arrays
- Arrays: fixed size,
length,[ ]indexing, can hold primitives. - ArrayLists: resizable,
size(),get/set, objects only.
Use an ArrayList when the number of items changes; an array when the size is fixed.
Comparing Integer objects: use equals or unbox to int, since == compares references for objects.
Check yourself
Which gives the number of elements in an ArrayList list?
Show the answer
list.size()
size().
5Going deeper: shifting indices, removing while traversing, and tracing
An ArrayList is a resizable list of objects.
ArrayList<String> names = new ArrayList<String>();
The methods
size(): number of elements.add(obj): appends to the end; returns true.add(index, obj): inserts at index; elements from there on shift right.get(index): returns the element.set(index, obj): replaces the element; returns the old one.remove(index): removes and returns the element; later elements shift left.
Valid indices are 0 to size() - 1 (and add(index, obj) also allows index == size()). Otherwise: IndexOutOfBoundsException.
Primitives are wrapped: use ArrayList<Integer> and ArrayList<Double>; autoboxing converts automatically.
Worked example (trace):
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(3);
list.add(8);
list.add(1, 7);
list.set(2, 9);
list.remove(0);
System.out.println(list);
- After three adds: [5, 3, 8].
add(1, 7): [5, 7, 3, 8].set(2, 9): [5, 7, 9, 8].remove(0): [7, 9, 8].- Output:
[7, 9, 8].
Removing while traversing: the classic trap. When an element is removed, everything after it moves down one place. A forward loop that then increments i skips the element that slid into the gap.
// BUGGY: misses the second of two neighboring matches
for (int i = 0; i < list.size(); i++) {
if (list.get(i) % 2 == 0) {
list.remove(i);
}
}
For [4, 6, 7]: i = 0 removes 4, leaving [6, 7]; i becomes 1 and looks at 7. The 6 is never checked.
Fix 1: go backward. Removals then affect only positions already visited.
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i) % 2 == 0) {
list.remove(i);
}
}
Fix 2: advance only when nothing was removed.
int i = 0;
while (i < list.size()) {
if (list.get(i) % 2 == 0) {
list.remove(i);
} else {
i++;
}
}
The same care applies to inserting during a forward traversal: after add(i, x), the original element is at i + 1; skip past it or the loop never ends.
Never add or remove inside an enhanced for loop over the same list: it throws a ConcurrentModificationException. Calling set is allowed in an indexed loop; and through the enhanced loop you can call mutator methods on the objects in the list, but you cannot replace the elements.
ArrayList against array
- Length:
list.size()againstarr.length. - Access:
list.get(i)againstarr[i]. - Change:
list.set(i, x)againstarr[i] = x. - Size: grows and shrinks against fixed.
- Contents: objects only against primitives or objects.
Standard algorithms carry over: sum, maximum, count, search, as with arrays, using get and size().
int max = list.get(0);
for (int v : list) {
if (v > max) {
max = v;
}
}
Building a new list of selected elements leaves the original unchanged and avoids the removal trap:
ArrayList<String> longWords = new ArrayList<String>();
for (String w : words) {
if (w.length() > 5) {
longWords.add(w);
}
}
Lists of objects: elements are references. list.get(0).setName("Ada") changes the object in the list. Compare elements with .equals.
Removing an Integer: list.remove(2) removes the element at index 2, not the value 2.
Efficiency: inserting or removing near the front makes every later element shift, so it is slower than working at the end.
Common mistakes
- Using
[ ]or.lengthwith an ArrayList. - Forgetting indices shift after
add(index, …)orremove. - Removing in a forward loop without adjusting.
- Modifying a list inside an enhanced for loop.
ArrayList<int>(must beInteger).- Using
seton an index that does not yet exist;setreplaces, it does not append.
Check yourself
After list holds [10, 20, 30, 40], what does list.remove(1) return, and what does the list then contain?
Show the answer
It returns 20; the list is [10, 30, 40]
remove(index) returns the removed element and shifts the rest left.
6For top marks
- Use
get(i), notlist[i], for ArrayLists. - When removing during traversal, loop backwards or adjust the index.
setandremovereturn the old element: useful in some free-response tasks.- Inserting at index
size()is allowed (appends); inserting beyond it throws IndexOutOfBoundsException.
a method that removes all words of a given length:
for (int i = words.size() - 1; i >= 0; i--) {
if (words.get(i).length() == len) words.remove(i);
}
Check yourself
For list = [4, 6, 9], what does list.set(1, 0) return?
Show the answer
6
The old value.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera