英文:
Java 11 not throwing ClassCastException when casting list of HashMap to list of String
问题
我在运行这段代码时期望出现ClassCastException,但它却没有问题地执行了,对于这种情况是否有解释?
英文:
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());
答案1
得分: 7
Java 泛型在运行时被擦除,因此类型转换无法进行检查。一旦您从结果列表中访问一个非字符串项,您将会收到 ClassCastException。这就是为什么此代码会生成未经检查的类型转换警告的原因。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论