Java 11在将HashMap列表强制转换为String列表时不会引发ClassCastException。

huangapple go评论66阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月19日 21:00:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定