ArrayList <?超级号码&gt;和双 [英] ArrayList &lt;? super Number&gt; and Double

查看:95
本文介绍了ArrayList <?超级号码&gt;和双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments .html#FAQ103
$ b


下界的通配符看起来像?super Type,并且代表
对于超类型为Type的所有类型的家族,键入Type
包含在内。类型称为下限。


那么为什么

 的ArrayList< ;?超级号码> psupn1 = new ArrayList< Number>(); 
psupn1.add(new Double(2));

已编译?



Double不是超类型编号1:

  ArrayList <?超级号码> pextn1 = new ArrayList< Number>(); 
psupn1.add(new Integer(2));
psupn1.add(new Double(2));
psupn1.add(new Float(2));
for(Number n:psupn1){// [Invalid] Number should be change to
// Object,即使我只能添加数字的子类型?



解决方案

因为无论类型参数 E 是什么,它都可以保证为 可以是 Number 或超类型......这意味着您可以从 Double 转换为 ë。你不能这样做:

  Number x = psupn1.get(0); 

虽然。



想一想,并尝试创建将在逻辑上破坏这个列表。例如,您不能使用:

  //无效
ArrayList<超级号码> psupn1 = new ArrayList< Integer>();
psupn1.add(new Double(2));

因为整数 不是 Number 或超类型 - 它是一个子类。你可以这样写:

  //有效的
ArrayList<扩展Number> psupn1 = new ArrayList< Integer>();

...因为这是相反的。在这一点上,你可以写:

  Number x = psupn1.get(0); 

因为列表中的任何元素都保证可以转换 。这是所有转换所需的 - 泛型类型参数或


From http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ103:

A wildcard with a lower bound looks like " ? super Type " and stands for the family of all types that are supertypes of Type , type Type being included. Type is called the lower bound .

So why

ArrayList<? super Number> psupn1 = new ArrayList<Number>();
psupn1.add(new Double(2));

compiled?

Double is not supertype of Number but subclass of Number...

Edit 1:

    ArrayList<? super Number> pextn1 = new ArrayList<Number>();
    psupn1.add(new Integer(2));
    psupn1.add(new Double(2));
    psupn1.add(new Float(2));
    for(Number n : psupn1){ // [Invalid] Number should be change to
    // Object even if I can only add subtype of Number??

    }

解决方案

You can add a Double to that, because whatever the type parameter E is, it's guaranteed to be either Number or a supertype... which means you can definitely convert from Double to E. You wouldn't be able to do:

Number x = psupn1.get(0);

though.

Think about it, and try to create lists which would logically break this. For example, you can't use:

// Invalid
ArrayList<? super Number> psupn1 = new ArrayList<Integer>();
psupn1.add(new Double(2));

because Integer isn't either Number or a supertype - it's a subclass. You can write:

// Valid
ArrayList<? extends Number> psupn1 = new ArrayList<Integer>();

... because that's the other way round. At that point you can write:

Number x = psupn1.get(0);

because any element in the list is guaranteed to be convertible to Number. It's all about which way the conversions are required - to the generic type parameter or from it.

这篇关于ArrayList <?超级号码&gt;和双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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