Unit 4 Cycle 2 Day 22: ArrayList: Type Safety

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

ArrayList: Type Safety

Section 4.4 — ArrayList Methods

Key Concept

ArrayList type safety means the generic type parameter restricts what elements can be added. An ArrayList only accepts String objects — adding an Integer causes a compile error. Without generics (ArrayList list = new ArrayList()), any object can be added, but you must cast when retrieving. The AP exam uses generics exclusively and tests that you understand type compatibility: subclass objects can be added to a superclass-typed list, but not vice versa.

Consider the following code segments.

// Segment A ArrayList list = new ArrayList(); list.add(42); // Segment B ArrayList nums = new ArrayList(); nums.add(3.14); // Segment C ArrayList vals = new ArrayList(); vals.add(5);

Which segment(s) compile without error?

Answer: (A) Only C

A: int to String list = type error. B: double to Integer list = type error. C: int autoboxed to Integer = valid.

Why Not the Others?

(B) A has a type mismatch (int to String).

(C) B has a type mismatch (double to Integer).

(D) A and B both fail.

Common Mistake

Generics enforce type safety. Autoboxing works for matching types (int to Integer) but not across types (double to Integer).

AP Exam Tip

ArrayList accepts int (autoboxed) but not double. Know autoboxing rules.

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.