问题
我有几个关于Java中通用通配符的问题:
- List <?之间有什么区别?扩展T>和List <?超级T>?
- 什么是有界通配符,什么是无界通配符?
#1 热门回答(111 赞)
在第一个问题中,<? extends T>
和<? super T>
是有界通配符的示例。无界通配符看起来像<?>
,基本上意味着<? extends Object>
。它松散地表示通用可以是任何类型。有界通配符(<? extends T>
or<? super T>
)通过声明它具有toextenda特定类型(<? extends T>
称为上限)或必须是特定类型的祖先(<? super T>
,称为下界)来对类型施加限制。
Java教程在文章Wildcards和More Fun with Wildcards中对泛型有一些非常好的解释。
#2 热门回答(44 赞)
如果你有一个类层次结构A,B是A的子类,而C和D都是B的子类,如下所示
class A {}
class B extends A {}
class C extends B {}
class D extends B {}
然后
List<? extends A> la;
la = new ArrayList<B>();
la = new ArrayList<C>();
la = new ArrayList<D>();
List<? super B> lb;
lb = new ArrayList<A>(); //fine
lb = new ArrayList<C>(); //will not compile
public void someMethod(List<? extends B> lb) {
B b = lb.get(0); // is fine
lb.add(new C()); //will not compile as we do not know the type of the list, only that it is bounded above by B
}
public void otherMethod(List<? super B> lb) {
B b = lb.get(0); // will not compile as we do not know whether the list is of type B, it may be a List<A> and only contain instances of A
lb.add(new B()); // is fine, as we know that it will be a super type of A
}
有界通配符类似于? extends B
,其中B是某种类型。也就是说,类型是未知的,但可以在其上放置"绑定"。在这种情况下,它受某些类的限制,这是B的子类。
#3 热门回答(38 赞)
Josh Bloch也很好地解释了何时使用super
和extends
在google io video talk这里他提到了制作人extends
Consumersuper
mnemonic。
从演示幻灯片:
假设你要将批量方法添加到Stack <E> void pushAll(Collection <?extends E> src); - src是E producer void popAll(Collection <?super E> dst); - dst是E消费者