Card 02/ 09
Generics Example: A List of Strings Refuses an Integer
One declaration, and a compile error that names the exact line that made the mistake.
Declaring List<String> makes the compiler reject any attempt to add something that is not a String. Adding a number to a list of order references shows the error, which 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, the <String> that says what the list holds, this would have compiled, run, and thrown a ClassCastException somewhere else entirely: in a method that reads the list, possibly in a different file.
Notice the <> on the right, called the diamond. The compiler infers the type argument from the declaration on the left, so writing new ArrayList<String>() is allowed and never necessary.
So the useful habit is to read a generics compile error as help rather than obstruction: it points at the line where the wrong value entered, which is the one line a run-time failure would never have named.
← → move through sections and cards