Unit 3 Cycle 2 Day 26: Class with Collection Field
Share
Class with Collection Field
Section Mixed — Review: Class Design
Key Concept
A class that contains a collection field (like an ArrayList) as an instance variable must carefully manage that collection in its constructor and methods. The constructor should initialize the collection, mutator methods should validate before adding, and accessor methods should protect against external modification. The AP exam tests classes that aggregate objects in a list and provide methods to search, filter, add, and remove elements. This pattern connects Unit 3 (class design) with Unit 4 (collections).
Consider the following class.
After executing Playlist p = new Playlist(3); p.add("A"); p.add("B"); p.add("C"); p.add("D");, what does p.size() return?
Answer: (B) 3
Capacity is 3. add("A"): count=1. add("B"): count=2. add("C"): count=3. add("D"): count(3) is NOT < length(3), so it is silently ignored. size() returns 3.
Why Not the Others?
(A) The fourth add is rejected because the array is full.
(C) Three songs were successfully added.
(D) The bounds check prevents any ArrayIndexOutOfBoundsException. The add is silently ignored.
Common Mistake
The add method checks capacity before adding. When full, it silently does nothing (no error, no exception). This is defensive programming.
AP Exam Tip
AP exam FRQs often require you to write add methods with bounds checking. Always verify there is room before adding to an array.