Unit 4 Cycle 2 Day 14: ArrayList: Removing Duplicates

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

ArrayList: Removing Duplicates

Section 4.5 — ArrayList Algorithms

Key Concept

Removing duplicates from an ArrayList requires checking each element against all subsequent elements. A nested loop where the inner loop checks for matches and removes them is the standard approach. Because removal shifts elements, the inner loop must handle index adjustment. An alternative approach adds unique elements to a new list using contains() to check for prior existence. The AP exam tests both approaches and asks whether the removal correctly handles consecutive and non-consecutive duplicates.

Consider the following code segment.

ArrayList list = new ArrayList(); list.add("a"); list.add("b"); list.add("a"); list.add("c"); list.add("b"); ArrayList unique = new ArrayList(); for (String s : list) { if (!unique.contains(s)) unique.add(s); } System.out.println(unique);

What is printed?

Answer: (A) [a, b, c]

Build unique: "a" new, add. "b" new, add. "a" exists, skip. "c" new, add. "b" exists, skip. Result: [a, b, c].

Why Not the Others?

(B) Duplicates are filtered. Only first occurrences kept.

(C) All three unique values are included.

(D) "b" is included since it first appears at index 1.

Common Mistake

contains() checks for existence. Building a new list with only unique elements preserves original order of first occurrences.

AP Exam Tip

Duplicate removal: new list + contains() check. Do not modify original during traversal.

Review this topic: Section 4.5 — ArrayList Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

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