Unit 4 Cycle 2 Day 14: ArrayList: Removing Duplicates
Share
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.
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.