0

I was expecting ClassCastExpection when running this code in Java 11 but it executes without an issue is there an explanation for this case?

List<?> list = List.of(new HashMap<>());
List<String> listOfStrings = (List<String>) list;
System.out.println("List size: " + listOfStrings.size());
Ehab Yassin
  • 151
  • 7

1 Answers1

7

Java generics are erased at runtime, so that cast cannot be checked. You'll get your ClassCastException once you access a not-String from the resulting list. This is why this code generates an unchecked cast warning.

Jorn
  • 20,612
  • 18
  • 79
  • 126