Unit 4 Cycle 2 Day 4: ArrayList Integer Removal Ambiguity

Unit 4 Advanced (Cycle 2) Day 4 of 28 Advanced

ArrayList Integer Removal Ambiguity

Section 4.4 — ArrayList Methods

Key Concept

The ArrayList removal ambiguity is one of the most tested traps on the AP exam. list.remove(3) calls remove(int index) and removes the element at position 3. To remove the Integer object with value 3, you must use list.remove(Integer.valueOf(3)) or list.remove((Integer) 3). This ambiguity only exists for ArrayList — for ArrayList, there is no confusion because String cannot be confused with an index.

Consider the following code segment.

ArrayList nums = new ArrayList(); nums.add(10); nums.add(20); nums.add(30); nums.remove(1); System.out.println(nums);

What is printed?

Answer: (A) [10, 30]

remove(1) removes the element at INDEX 1 (which is 20), not the element with VALUE 1. Result: [10, 30].

Why Not the Others?

(B) remove(1) does change the list.

(C) Index 0 (value 10) is not removed.

(D) Index 2 (value 30) is not removed.

Common Mistake

For ArrayList, remove(1) removes at INDEX 1. To remove the value 1, use remove(Integer.valueOf(1)).

AP Exam Tip

Integer ArrayList trap: remove(int) = by index. remove(Integer) = by value. The AP exam tests this ambiguity directly.

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.