实例化类型的泛型类<?> [英] Instantiating a Generic Class of Type <?>

查看:121
本文介绍了实例化类型的泛型类<?>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例代码实例化了两个通用集合:

p>

 列表<?> list = new ArrayList<?>(); 
List< ;? extends Object> list2 = new ArrayList< ;? extends Object>();

问题的正确答案是这个代码会编译,但添加到任何一个集合将产生运行时错误。



当我尝试编译这样的代码,我只是得到错误。 Java教程甚至不显示这种类型的代码,它通常使用通配符作为上传的一部分。

  Collection< > c = new ArrayList< String>(); 

上述两个通用集合是否甚至是合法代码?第二个由我的逻辑只会禁止接口。第一个看起来完全没用。为什么使用一个通用的,没有尝试在控制?

解决方案

查看优秀的 Java泛型教程PDF 。更具体地,关于通配符的部分包含对您的问题的回答,我引用

 集合<?& c = new ArrayList< String>(); 
c.add(new Object());




因为我们不知道 c 代表,我们不能
添加对象。 add()方法接受类型 E 的参数,集合的
元素类型。当实际类型参数
时,它代表一些未知类型。我们传递的任何参数将
必须是这个未知类型的子类型。因为我们不知道
类型是什么,我们不能传递任何东西。唯一的例外是 null
它是每个类型。



I'm studying for the SCJP/OCPJP and I came across a sample question that seams strange to me.

The sample code instantiated two generic collections:

List<?> list = new ArrayList<?>();
List<? extends Object> list2 = new ArrayList<? extends Object>();

The "correct" answer to the question was that this code would compile but adding to either collection would produce a runtime error.

When I try to compile code like this I just get errors. The Java tutorial does not even show this type of code, it instead usually uses wildcards as a part of an upcast.

Collection<?> c = new ArrayList<String>();

Are the two generic collections above even legitimate code? The second by my logic would only disallow interfaces. The first one looks completely useless. Why use a generic that makes no attempt at control?

解决方案

Check out the excellent Java generics tutorial PDF. More specifically the section about wildcards contains the answer to your question, and I quote

Collection<?> c = new ArrayList<String>();
c.add( new Object() );

Since we don’t know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don’t know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.

这篇关于实例化类型的泛型类&lt;?&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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