Unit 3 Cycle 2 Day 26: Class with Collection Field

Unit 3 Advanced (Cycle 2) Day 26 of 28 Advanced

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.

public class Playlist { private String[] songs; private int count; public Playlist(int capacity) { songs = new String[capacity]; count = 0; } public void add(String song) { if (count < songs.length) { songs[count] = song; count++; } } public int size() { return count; } }

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.

Review this topic: Section Mixed — Review: Class Design • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

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