Java 泛型(通配符)

新手上路,请多包涵

我有几个关于 Java 中通用通配符的问题:

  1. List<? extends T>List<? super T> 有什么区别?

  2. 什么是有界通配符,什么是无界通配符?

原文由 Pablo Fernandez 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 437
2 个回答

在你的第一个问题中, <? extends T><? super T> 是有界通配符的例子。无限通配符看起来像 <?> ,基本上意味着 <? extends Object> 。它大致意味着泛型可以是任何类型。有界通配符( <? extends T><? super T> )通过说它必须 扩展 特定类型( <? extends T> )来限制类型(—e3165a25db03d639c207b38b309—)界),或者必须是特定类型的祖先( <? super T> 被称为下界)。

Java 教程在文章 WildcardsMore Fun with Wildcards 中对泛型有一些很好的解释。

原文由 Bill the Lizard 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题