Card 04/ 09
All 9 cards
GotchaDifficulty: Intermediate1 min
Why a List<String> Is Not a List<Object>
A String is an Object, and every method taking an Object accepts one. A List<String> handed to a method taking List<Object> is refused, which reads like an inconsistency.
Report.java:8: error: incompatible types: List<String> cannot be converted to List<Object>Imagine it were allowed. The method would be holding something it believes is a list of objects, and nothing would stop it from doing this.
void spoil(List<Object> anything) {
anything.add(42);
}
List<String> refs = new ArrayList<>();
spoil(refs);
String first = refs.get(0);Line 2 is legal for a list of objects. Line 8 would then fail with a ClassCastException on a list whose declaration promised it held only strings — which is exactly the failure generics exist to remove.
When a method genuinely only reads, say so with a wildcard: List<? extends Object>, usually written List<?>. That accepts a list of anything and refuses to add to it, which is the combination that makes it safe.