泛型类型的Java容器 [英] Java containers of generic types
问题描述
I am preparing for an exam and one of the codes we were given by professor is obscure to me:
我准备参加考试,其中一位教授给我的代码很隐晦: Z {
static java.util.LinkedList<?扩展对象> a =
new java.util.LinkedList< String>();
public static void main(String [] args){
a.add(null); // 1
.add(new Object()); // 2
a.add(new Object()); // 3
System.out.println(a); // 4
}
}
public class Z {
static java.util.LinkedList<? extends Object> a =
new java.util.LinkedList<String>();
public static void main(String[] args) {
a.add(null); // 1
a.add(new Object()); // 2
a.add("new Object()"); // 3
System.out.println(a); // 4
}
}
NetBeans在这里给我提供了非常奇怪的编译错误:
NetBeans gives me really strange compilation errors here:
no suitable method found for add(java.lang.Object)
method java.util.LinkedList.add(capture#1 of ? extends java.lang.Object) is not applicable
(actual argument java.lang.Object cannot be converted to capture#1 of ? extends java.lang.Object by method invocation conversion)
no suitable method found for add(java.lang.String)
method java.util.LinkedList.add(capture#2 of ? extends java.lang.Object) is not applicable
(actual argument java.lang.String cannot be converted to capture#2 of ? extends java.lang.Object by method invocation conversion)
任何人都可以向我解释这些错误吗?我非常确定应该可以将String对象添加到此列表中。
Could anyone please explain me these errors? I was pretty sure that it should be possible to add String objects to this list.
推荐答案
PECS - Producer扩展,Consumer super - 这是布洛克提出的一个助记符,以应付上述情况。
PECS - Producer extends, Consumer super - this is a mnemonic proposed by Bloch to cope with the above.
换句话说,如果您使用 extends
您只能从您的收藏中产生元素。如果你想要它消耗元素 - 使用 super
。
In other words, if you use extends
you can only produce elements from your collection. If you want it to consume elements - use super
.
关键是强制编译时安全。如果您的收藏是使用定义的?扩展SomeBaseClass
,这意味着它可以包含基类的单个子类的实例。在你的情况下,你正在定义新的LinkedList< String>()
,但你尝试添加一个 Object
- 这应该不被允许,并且被编译器捕获。
The point of that is to enforce compile-time safety. If your collection was defined with ? extends SomeBaseClass
, this would mean "It can contain instances of a single subclass of the base class". In your case you are defining new LinkedList<String>()
, but you try to add an Object
- this should not be allowed, and it is caught by the compiler.
这篇关于泛型类型的Java容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!