Card 02/ 09
All 9 cards
ExampleDifficulty: Intermediate1 min
A List of Strings That Cannot Be Handed an Integer
One declaration, and the error that arrives before anything runs.
List<String> refs = new ArrayList<>();
refs.add("AB-1");
refs.add(42);Refs.java:3: error: incompatible types: int cannot be converted to String
refs.add(42);
^The error names the line that made the mistake. Without the type parameter this would have compiled, run, and thrown a ClassCastException somewhere else entirely — in a method that reads the list, possibly in a different file.
What to notice is the <> on the right. The compiler infers the type argument from the declaration, so writing new ArrayList<String>() is allowed and never necessary.