Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Generics — Wildcards, Bounded Types, PECS

Why can't you assign a List<String> to a List<Object>, even though String is an Object?

Level II · JuniorGenerics — Wildcards, Bounded Types, PECS
Short answer

Generics are invariant precisely to preserve type safety: if List<String> were a List<Object>, you could add an Integer through the Object-typed reference and then read a String back, causing a ClassCastException — the exact problem generics exist to prevent.

Explanation

Arrays, by contrast, are covariant (Object[] can hold a String[]) and therefore unsafe, throwing ArrayStoreException at runtime. When you need flexibility across subtypes you use a bounded wildcard rather than relying on subtyping of the parameterized type.

Common mistakes
  • Saying generics are covariant like arrays.
  • Not explaining the heap pollution that covariance would allow.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Generics — Wildcards, Bounded Types, PECS.

Practise free

More on Generics — Wildcards, Bounded Types, PECS