Unit 4 Cycle 2 Day 22: ArrayList: Type Safety
Share
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.
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.