Video in progress
On which line does the ClassCastException occur in this code, and why exactly there?
List<String> names = new ArrayList<>();
legacyFill(names);
for (String n : names) {
System.out.println(n.toUpperCase());
}
static void legacyFill(List list) { // raw type
list.add("ali");
list.add(42);
}
Not at add, but in the for loop. An Integer got into the List<String> through a raw type, and the compiler put the cast at the place where elements are read.
📖 Answer
When you work with a raw List, the generic check is switched off, and the compiler only gives an "unchecked" warning. At runtime, an ArrayList holds a plain Object[], and adding 42 to it is no problem.
The compiler puts the cast at the read site. The for loop actually compiles to this:
Iterator it = names.iterator();
while (it.hasNext()) {
String n = (String) it.next(); // CCE on the second iteration
...
}
The first element prints "ALI", then ClassCastException: Integer cannot be cast to String.
What's bad in prod is that the error appears far from where the poison went in: in another service, in another request. What to do:
- compile with
-Xlint:unchecked -Werrorand don't ignore raw type warnings; - at the boundary with an old API, use
Collections.checkedList(names, String.class): it fails at the moment the wrong element is added, and the stack trace points to the culprit; - if an external library returns a raw type, check it right away and move it into a typed collection.
Sign up to mark studied questions and save your progress.