我正在学习 SCJP/OCPJP,我遇到了一个对我来说很奇怪的示例问题。
示例代码实例化了两个通用集合:
List<?> list = new ArrayList<?>();
List<? extends Object> list2 = new ArrayList<? extends Object>();
问题的“正确”答案是该代码可以编译,但添加到任一集合都会产生运行时错误。
当我尝试编译这样的代码时,我只会收到错误。 Java 教程甚至没有显示这种类型的代码,它通常使用通配符作为向上转换的一部分。
Collection<?> c = new ArrayList<String>();
上面的两个通用集合是合法代码吗?按照我的逻辑,第二个只会禁止接口。第一个看起来完全没用。为什么要使用不尝试控制的仿制药?
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?
发布评论
评论(4)
看看优秀的Java 泛型教程 PDF。更具体地说,有关通配符的部分包含您问题的答案,我引用
Check out the excellent Java generics tutorial PDF. More specifically the section about wildcards contains the answer to your question, and I quote
如果你想在运行时声明 Type,你可以这样做:
If you want to declare Type at runtime, you can do something like this:
我之前在这个答案中回答过这个问题。
?
不能在实例化中使用。我不知道为什么它说代码可以编译,我使用过的 java 编译器都不允许这样做。您可以通过以下方式执行上面显示的操作:这将编译并运行,但您不能这样做:
I answered this somewhat before in this answer.
?
cannot be used in the instantiation. I'm not sure why it says the code would compile, none of the java compilers I have used would allow that. You could do what is shown above by the following:That would compile and run, but you couldn't do:
new
生成对象的具体实例。具体实例只能有一种类型,包括任何泛型。知道这一点后,通配符就不能与new
一起使用。new
produces a concrete instance of an object. The concrete instance can have only one type, including any generics. Knowing this, wildcards cannot work withnew
.