Pab*_*dez 106 java generics bounded-wildcard
我有几个关于Java中通用通配符的问题:
List<? extends T>和之间有什么区别List<? super T>?
什么是有界通配符,什么是无界通配符?
Bil*_*ard 119
在你的第一个问题,<? extends T>而且<? super T>是有界通配符的例子.一个无界的通配符看起来像<?>,基本上意味着<? extends Object>.它松散地意味着通用可以是任何类型.有界通配符(<? extends T>或<? super T>)通过声明它必须扩展特定类型(<? extends T>称为上限)或必须是特定类型的祖先(<? super T>称为下限)对类型施加限制.
Java教程在通配符和使用通配符更有趣的文章中对泛型有一些非常好的解释.
oxb*_*kes 48
如果你有一个类层次结构A,B是A的子类,而C和D都是B的子类,如下所示
class A {}
class B extends A {}
class C extends B {}
class D extends B {}
Run Code Online (Sandbox Code Playgroud)
然后
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
}
Run Code Online (Sandbox Code Playgroud)
有界通配符就像? extends BB是某种类型.也就是说,类型是未知的,但可以在其上放置"绑定".在这种情况下,它受某些类的限制,这是B的子类.