使用泛型类型执行转换时出现警告 [英] Warning when performing cast with generic types

查看:116
本文介绍了使用泛型类型执行转换时出现警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ...我不明白为什么我会收到警告(未经检查的转换)。 
地图< ;? estends SomeType,SomeOtherType>地图;
...
映射< SomeType,SomeOtherType> castedMap =(地图< SomeType,SomeOtherType>)地图;
...

我的意思是将castedMap发布到外部代码的危险是什么?
这两种操作都可以在运行时完美运行:
$ b


  • 使用SomeType类型的键获取castedMap中的元素
  • 使用SomeType类型的键将元素放在castedMap中。



我会简单地用@SuppressWarnings(unchecked)取消警告。 。

解决方案

无聊的答案可能是:当有警告时,它不是类型安全的。就是这样。



为什么它不是类型安全的,可以在这个例子中看到:

  import java.util.HashMap; 
import java.util.Map;

类SomeType {}
类SomeSubType extends SomeType {} $ b $ class SomeOtherType {}

公共类CastWarning
{
public static void main(String [] args)
{
Map&SomeSubType,SomeOtherType> originalMap = new HashMap< SomeSubType,SomeOtherType>();
地图< ;?扩展SomeType,SomeOtherType> map = originalMap;
Map< SomeType,SomeOtherType> castedMap =(地图< SomeType,SomeOtherType>)地图;

//因铸造而有效:映射的
//键不是SomeType,而是SomeSubType
//的信息已被抛弃。 ..
SomeType someType = new SomeType();
SomeOtherType someOtherType = new SomeOtherType();
castedMap.put(someType,someOtherType);

//对于自身有效,但由于未经检查的映射转换导致ClassCastException
// $ b $ SomeSubType someSubType = originalMap.keySet()。iterator()。next ();
}
}


I do not understand why I get a warning (unchecked cast) when I try to perform this:

...
Map<? estends SomeType, SomeOtherType> map;
...
Map<SomeType, SomeOtherType> castedMap = (Map<SomeType, SomeOtherType>) map;
...

I mean what is the danger of publishing castedMap to an outside code? Both opperations will work perfectly at runtime:

  • getting elements from castedMap using key of type SomeType
  • putting elements in castedMap using key of type SomeType.

I would simply suppress warnings using @SuppressWarnings("unchecked").

解决方案

As boring as the answer may be: When there is a warning, then it's not type-safe. That's it.

Why it is not type safe can be seen in this example:

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();
    }
}

这篇关于使用泛型类型执行转换时出现警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆