我们是否可以在实例化期间使用通配符 [英] Are we allowed to use wildcard during instantiation

查看:62
本文介绍了我们是否可以在实例化期间使用通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这些声明在Java中无效?

why are these declaration invalid in Java?

  1. List< Number>测试=新的ArrayList< ;?扩展Number>();

列表测试=新的ArrayList< ;?扩展Number>();

在实例化期间我们是否不允许使用通配符.并且通配符仅对将它们传递给方法有用吗?

are we not allowed to use wildcard during instantiation. and if the wildcards are only useful for passing them to methods?

List< Object>test = new ArrayList< Integer>(); 是非法的,因为泛型不是协变正确的?

and List<Object> test = new ArrayList<Integer>(); is illegal because generics are not covariant correct?

推荐答案

?通配符表示未知"而不是任何".实例化一个未知内容的新容器没有任何意义,您将在其中放置什么?它真的不能用于任何东西!

The ? wildcard character means "unknown" not "any". It doesn't make any sense to instantiate a new container of unknown contents, what would you put in there? It can't really be used for anything!

那么声明 new ArrayList< ;?扩展Number>()的意思是某些扩展数字的特定事物,但我不知道是什么."不是是指任何扩展数字的内容."
您分配给它的 List< Number> 将允许同时添加Double和Integer,但是 List< ;?的实际内容是?扩展Number> 可能是Float!(或其他任何内容).请考虑一下,如果通配符充当"Any",那么在代码中会发生什么:

So the declaraion new ArrayList<? extends Number>() Means "some specific thing that extends number, but I don't know what." It does not mean "anything that extends number."
The List<Number> you assigned it to would allow both Double and Integer to be added to it, but the actual contents of a List<? extends Number> might be Float! (or whatever else.) Consider what would happen in this code if the wildcard worked as an "Any":

    List<Integer> listInteger = new ArrayList<Integer>();
    listInteger.add(Integer.valueOf(1));
    List<? extends Number> listWildCard = listInteger;
    listWildCard.add(Double.valueOf(1.0)); //This does not compile
    Integer integer = listInteger.get(1);//because this would throw a ClassCastException

关于第二个示例的脚注:使用原始类型调用不带类型参数的参数化类型.这被认为是编程错误.该语法仅是合法的,因此仍可以编译在Java 5之前编写的代码.如果您的方案与Java 5之前的版本不具有向后兼容性,请不要这样做.

Footnote regarding your second example: Declaring a paramaterized type with no type parameter is called using the Raw Type. This is considered a programming error. The syntax is only legal so that code written before java 5 still compiles. Just don't do it if your scenario isn't backward compatability with pre-java 5.

这篇关于我们是否可以在实例化期间使用通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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