Java Generics (Wildcards)
2022-08-31 08:56:58
我有几个关于Java中通用通配符的问题:
和 有什么区别?
List<? extends T>
List<? super T>
什么是有界通配符,什么是无界通配符?
我有几个关于Java中通用通配符的问题:
和 有什么区别?List<? extends T>
List<? super T>
什么是有界通配符,什么是无界通配符?
如果你有一个类层次结构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
}
有界通配符类似于 B 是某种类型。也就是说,类型是未知的,但可以在其上放置“绑定”。在这种情况下,它由某个类限定,该类是B的子类。? extends B