我有几个关于 Java 中通用通配符的问题:
List<? extends T>
和List<? super T>
有什么区别?什么是有界通配符,什么是无界通配符?
原文由 Pablo Fernandez 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有几个关于 Java 中通用通配符的问题:
List<? extends T>
和 List<? super T>
有什么区别?
什么是有界通配符,什么是无界通配符?
原文由 Pablo Fernandez 发布,翻译遵循 CC BY-SA 4.0 许可协议
If you have a class hierarchy A
, B
is a subclass of A
, and C
and D
are 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 的子类。
原文由 oxbow_lakes 发布,翻译遵循 CC BY-SA 4.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
在你的第一个问题中,
<? extends T>
和<? super T>
是有界通配符的例子。无限通配符看起来像<?>
,基本上意味着<? extends Object>
。它大致意味着泛型可以是任何类型。有界通配符(<? extends T>
或<? super T>
)通过说它必须 扩展 特定类型(<? extends T>
)来限制类型(—e3165a25db03d639c207b38b309—)界),或者必须是特定类型的祖先(<? super T>
被称为下界)。Java 教程在文章 Wildcards 和 More Fun with Wildcards 中对泛型有一些很好的解释。