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

问题描述



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

p>

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

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



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

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

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

解决方案

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

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




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

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

07-31 08:53