使用泛型类型执行强制转换时的警告

使用泛型类型执行强制转换时的警告,第1张

使用泛型类型执行强制转换时的警告

答案可能很无聊:出现警告时,它不是类型安全的。而已。

__在此示例中可以看到 为什么 它不是类型安全的:

import java.util.HashMap;import java.util.Map;class SomeType {}class SomeSubType extends SomeType {}class SomeOtherType {}public class CastWarning{    public static void main(String[] args)    {        Map<SomeSubType, SomeOtherType> originalMap = new HashMap<SomeSubType, SomeOtherType>();        Map<? extends SomeType, SomeOtherType> map = originalMap;        Map<SomeType, SomeOtherType> castedMap = (Map<SomeType, SomeOtherType>) map;        // Valid because of the cast: The information that the        // key of the map is not "SomeType" but "SomeSubType"        // has been cast away...        SomeType someType = new SomeType();        SomeOtherType someOtherType = new SomeOtherType();        castedMap.put(someType, someOtherType);        // Valid for itself, but causes a ClassCastException        // due to the unchecked cast of the map        SomeSubType someSubType = originalMap.keySet().iterator().next();    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5507224.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存