< 之间的区别?超级T>和 <?扩展 T>在 Java 中 [英] Difference between <? super T> and <? extends T> in Java

查看:23
本文介绍了< 之间的区别?超级T>和 <?扩展 T>在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<有什么区别?super T>List ?

我曾经使用 List,但它不允许我向它添加元素 list.add(e),而 List 确实如此.

I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List<? super T> does.

推荐答案

extends

Listfoo3 表示这些都是合法的赋值:

extends

The wildcard declaration of List<? extends Number> foo3 means that any of these are legal assignments:

List<? extends Number> foo3 = new ArrayList<Number>();  // Number "extends" Number (in this context)
List<? extends Number> foo3 = new ArrayList<Integer>(); // Integer extends Number
List<? extends Number> foo3 = new ArrayList<Double>();  // Double extends Number

  1. 读取 - 鉴于上述可能的分配,您保证从 List foo3 读取什么类型的对象:

  1. Reading - Given the above possible assignments, what type of object are you guaranteed to read from List foo3:

  • 您可以读取 Number 因为任何可以分配给 foo3 的列表都包含一个 NumberNumber 的子类.
  • 您无法读取 Integer,因为 foo3 可能指向 List.
  • 您无法读取 Double,因为 foo3 可能指向 List.
  • You can read a Number because any of the lists that could be assigned to foo3 contain a Number or a subclass of Number.
  • You can't read an Integer because foo3 could be pointing at a List<Double>.
  • You can't read a Double because foo3 could be pointing at a List<Integer>.

Writing - 鉴于上述可能的分配,您可以将什么类型的对象添加到 List foo3所有人> 以上可能的 ArrayList 赋值:

Writing - Given the above possible assignments, what type of object could you add to List foo3 that would be legal for all the above possible ArrayList assignments:

  • 您不能添加 Integer,因为 foo3 可能指向 List.
  • 您不能添加 Double,因为 foo3 可能指向 List.
  • 您不能添加Number,因为foo3 可能指向List.
  • You can't add an Integer because foo3 could be pointing at a List<Double>.
  • You can't add a Double because foo3 could be pointing at a List<Integer>.
  • You can't add a Number because foo3 could be pointing at a List<Integer>.

您不能将任何对象添加到 List 因为你不能保证它真正指向的是什么类型的 List,所以你不能保证该对象在那个 List 中是允许的>.唯一的保证"是您只能从中读取,并且您将获得 TT 的子类.

You can't add any object to List<? extends T> because you can't guarantee what kind of List it is really pointing to, so you can't guarantee that the object is allowed in that List. The only "guarantee" is that you can only read from it and you'll get a T or subclass of T.

现在考虑 List <?超级T>.

Listfoo3 表示这些都是合法的赋值:

The wildcard declaration of List<? super Integer> foo3 means that any of these are legal assignments:

List<? super Integer> foo3 = new ArrayList<Integer>();  // Integer is a "superclass" of Integer (in this context)
List<? super Integer> foo3 = new ArrayList<Number>();   // Number is a superclass of Integer
List<? super Integer> foo3 = new ArrayList<Object>();   // Object is a superclass of Integer

  1. 阅读 - 鉴于上述可能的分配,当您从 List foo3 中读取时,您保证会收到什么类型的对象:

  1. Reading - Given the above possible assignments, what type of object are you guaranteed to receive when you read from List foo3: