gpt4 book ai didi

java逆变疑问

转载 作者:行者123 更新时间:2023-12-01 19:53:37 25 4
gpt4 key购买 nike

我读过这篇关于逆变的文章:

Let's now introduce another wildcard: ? super. Given a supertype B of a type A, then C<B> is a subtype of C<? super A>:

List<Fruit> fruits = new ArrayList<Fruit>();
List<? super Apple> = fruits;

但是为什么C<B>是子类型而不是父类(super class)型?

最佳答案

List<? super Apple表示 Apple 的一些未知父类(super class)型的列表。在这样的变量中,您可以输入 List<Apple> , List<Fruit> (假设 FruitApple 的父类(super class)型)或 List<Object> ,例如。

这正是父类(super class)型的含义:List<? super Apple>List<Apple> 更通用.

  • 进入List<Apple>可以放苹果,其他什么都可以。从列表中得到的所有东西都是苹果。
  • 进入List<? super Apple>你可以放苹果(没有别的,因为你不知道确切的类型)。从列表中得到的所有内容都是一个对象,但我们不知道是什么类型的对象(例如,因为它可能是 List<Object> )。

如果我们使用List<? extends Apple> ,它是类似的:这意味着 Apple 的一些未知子类型的列表。 。这可能是 List<Apple> , List<GoldenDelicious> , List<GrannySmith> , List<Jonagold>等等。

  • 进入List<Apple>你可以放苹果(所有类型的苹果),从中得到的一切都是苹果。
  • 进入List<? extends Apple>你不能输入任何东西 - 因为你不知道实际使用的是 Apple 的哪种子类型。但我们从中得到的一切实际上都是一个苹果。

我们可以用 List<Apple>所有事情,甚至更多List<? super Apple>或与 List<? extends Apple> - 例如它是这两种通配符类型的子类型

(这同样适用于所有泛型类型及其通配符变体,只是对于列表和类似的容器类型更容易查看。)

关于java逆变疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6859903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com