Unit 4 Cycle 1 Day 11: ArrayList remove()

Unit 4 Foundation (Cycle 1) Day 11 of 28 Foundation

ArrayList remove()

Section 4.4 — ArrayList Methods

Key Concept

The ArrayList.remove() method has two forms that can cause confusion with Integer lists. remove(int index) removes the element at the specified index, while remove(Object obj) removes the first occurrence of the object. For an ArrayList, calling list.remove(3) removes the element at index 3, not the element with value 3. To remove the value 3, use list.remove(Integer.valueOf(3)). The AP exam tests this ambiguity explicitly.

Consider the following code segment.

ArrayList list = new ArrayList(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.remove(1); System.out.println(list.size() + " " + list.get(1));

What is printed?

Answer: (A) 3 C

After adds: [A, B, C, D]. remove(1) removes "B": [A, C, D]. Size=3. get(1) returns "C" (shifted from index 2 to 1).

Why Not the Others?

(B) remove() decreases the size by 1. Size is 3, not 4.

(C) "B" was removed. "C" shifted to index 1.

(D) Both size and element are different after removal.

Common Mistake

When an element is removed from an ArrayList, all subsequent elements shift left and the size decreases by 1. The indices of all elements after the removed one change.

AP Exam Tip

After remove(i): size decreases by 1, elements after index i shift left. get(i) now returns what was at i+1.

Review this topic: Section 4.4 — ArrayList Methods • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.