College Board Unit 4
How it works
The two-argument add(index, value) inserts at a position and shifts every later element one slot to the right, increasing size by one. The remove(index) call deletes an element, shifts later elements left, and returns the removed value. Because both operations renumber everything after the change point, the index that was correct before the call is usually not correct after it.
When removing inside a loop, either iterate backwards or avoid advancing the index after a removal.
Common error
Removing while iterating forwards with a normal increment, which silently skips the element after each removal.
Worked example
Java
ArrayList<String> list = new ArrayList<String>();
list.add("A"); list.add("C");
list.add(1, "B");
System.out.println(list.remove(0));
System.out.println(list);Output
A
[B, C]Insertion creates a slot at index 1; removal closes the gap at index 0.
Exercises
6.2.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(10); list.add(20); list.add(30);
list.remove(1);
System.out.println(list);Show solution
Output
[10, 30]The integer argument selects index 1, so the value 20 is removed.
6.2.2 · Write code
Write public static void removeZeros(ArrayList<Integer> values). Remove every zero in place, including consecutive zeros, without skipping elements.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public static void removeZeros(ArrayList<Integer> values) {
for (int i = values.size() - 1; i >= 0; i--) {
if (values.get(i) == 0) values.remove(i);
}
}Check your code
Java
ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(0,0,3,0));
removeZeros(a); System.out.println(a);
ArrayList<Integer> b = new ArrayList<Integer>(); removeZeros(b); System.out.println(b);Expected output
[3]
[]