List<之间的区别是什么?super T>和List<?延伸T> ?

我曾经使用List<?扩展T>,但它不允许我添加元素到它的List .add(e),而List<?super T>有。


当前回答

这里最令人困惑的是,无论我们指定了什么类型限制,赋值只能以一种方式工作:

baseClassInstance = derivedClassInstance;

您可能认为Integer扩展了Number,并且Integer可以作为<?扩展数字>,但是编译器会告诉你<?extends Number>不能转换为Integer(也就是说,在人类的说法中,任何扩展Number的东西都可以转换为Integer是错误的):

class Holder<T> {
    T v;
    T get() { return v; }
    void set(T n) { v=n; }
}
class A {
    public static void main(String[]args) {
        Holder<? extends Number> he = new Holder();
        Holder<? super Number> hs = new Holder();

        Integer i;
        Number n;
        Object o;

        // Producer Super: always gives an error except
        //       when consumer expects just Object
        i = hs.get(); // <? super Number> cannot be converted to Integer
        n = hs.get(); // <? super Number> cannot be converted to Number
                      // <? super Number> cannot be converted to ... (but
                      //       there is no class between Number and Object)
        o = hs.get();

        // Consumer Super
        hs.set(i);
        hs.set(n);
        hs.set(o); // Object cannot be converted to <? super Number>

        // Producer Extends
        i = he.get(); // <? extends Number> cannot be converted to Integer
        n = he.get();
        o = he.get();

        // Consumer Extends: always gives an error
        he.set(i); // Integer cannot be converted to <? extends Number>
        he.set(n); // Number cannot be converted to <? extends Number>
        he.set(o); // Object cannot be converted to <? extends Number>
    }
}

hs.set(我);是可以的,因为Integer可以转换为Number的任何超类(而不是因为Integer是Number的超类,这不是真的)。

EDIT添加了一条关于消费者扩展和生产者超级的注释——它们没有意义,因为它们相应地指定了什么,而只是对象。建议您记住PECS,因为CEPS从来都没有用。

其他回答

何时使用extends和super

通配符在方法参数中最有用。它们允许方法接口中必要的灵活性。

人们经常混淆什么时候使用扩展,什么时候使用超边界。经验法则是“得到-放”原则。如果您从参数化容器中获取某些内容,请使用extends。

int totalFuel(List<? extends Vehicle> list) {
int total = 0;
for(Vehicle v : list) {
    total += v.getFuel();
}
return total;}

totalFuel方法从列表中获取车辆,询问它们有多少燃料,并计算总数。 如果将对象放入参数化容器中,请使用super。

int totalValue(Valuer<? super Vehicle> valuer) {
int total = 0;
for(Vehicle v : vehicles) {
    total += valuer.evaluate(v);
}
return total;}

totalValue方法将车辆放入Valuer中。 知道扩展界比super更常见是很有用的。

使用只能从集合中获得的扩展。你不能投入进去。此外,虽然超级允许获取和放置,在获取期间的返回类型是?超级T。

的例子, 假设继承顺序为O > S > T > U > V

使用extends关键字,

正确的:

List<? extends T> Object = new List<T>();
List<? extends T> Object = new List<U>();
List<? extends T> Object = new List<V>();

不正确的:

List<? extends T> Object = new List<S>();
List<? extends T> Object = new List<O>();

超级关键字:

正确的:

List<? super T> Object = new List<T>();
List<? super T> Object = new List<S>();
List<? super T> Object = new List<O>();

不正确的:

List<? super T> Object = new List<U>();
List<? super T> Object = new List<V>();

添加对象: List对象= new List();

Object.add(new T()); //error

但是为什么会出错呢? 让我们看看初始化列表对象的可能性

List<? extends T> Object = new List<T>();
List<? extends T> Object = new List<U>();
List<? extends T> Object = new List<V>();

如果我们使用Object。添加(新T ());那么只有当

List<? extends T> Object = new List<T>(); 

但还有另外两种可能

List对象= new List(); List对象= new List(); 如果我们尝试将(new T())添加到上述两个可能性中,它将会给出一个错误,因为T是U和V的高级类。我们尝试添加一个T对象[它是(new T())]到类型为U和V的列表。高级类对象(基类)不能传递给低级对象(子类)。

由于额外的两种可能性,即使你使用了正确的可能性,Java也会给你错误,因为Java不知道你所指的对象是什么,所以你不能向List中添加对象Object = new List();因为有不成立的可能性。

添加对象: List对象= new List();

Object.add(new T()); // compiles fine without error
Object.add(new U()); // compiles fine without error
Object.add(new V()); // compiles fine without error

Object.add(new S()); //  error
Object.add(new O()); //  error

但是为什么上面两个会出现错误呢? 我们可以使用Object。添加(新T ());只有在以下的可能性中,

List<? super T> Object = new List<T>();
List<? super T> Object = new List<S>();
List<? super T> Object = new List<O>();

如果我们尝试使用Object。add(new T()) in List对象= new List(); 而且 List对象= new List(); 那么它就会给出错误 这是因为 我们不能将T对象[which is new T()]添加到List object = new List();因为它是U类型的对象。我们不能给U对象添加一个T对象[它是新的T()],因为T是一个基类,U是一个子类。我们不能将基类添加到子类,这就是发生错误的原因。另一种情况也是一样的。

向列表中添加一个项目:

列表< ?extends X >不允许向列表中添加任何东西,除了null。 列表< ?super X >允许添加任何-a X (X或其子类型),或null。

从列表中获取一项:

当你从List< ?扩展X >,你可以将它赋值给X类型的变量或X的任何超类型,包括Object。 当你从List< ?super X >,你只能将它分配给Object类型的变量。

一些例子:

    List<? extends Number> list1 = new ArrayList<Integer>();
    list1.add(null);  //OK
    Number n = list1.get(0);  //OK
    Serializable s = list1.get(0);  //OK
    Object o = list1.get(0);  //OK

    list1.add(2.3);  //ERROR
    list1.add(5);  //ERROR
    list1.add(new Object());  //ERROR
    Integer i = list1.get(0);  //ERROR

    List<? super Number> list2 = new ArrayList<Number>();
    list2.add(null);  //OK
    list2.add(2.3);  //OK
    list2.add(5);  //OK
    Object o = list2.get(0);  //OK

    list2.add(new Object());  //ERROR
    Number n = list2.get(0);  //ERROR
    Serializable s = list2.get(0);  //ERROR
    Integer i = list2.get(0);  //ERROR

扩展

List<?数字> foo3意味着这些都是合法的赋值:

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

Reading - Given the above possible assignments, what type of object are you guaranteed to read from List foo3: 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 - 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: 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<?extends t>因为你不能保证它真正指向的是什么样的List,所以你不能保证对象被允许在那个List中。唯一的“保证”是你只能读取它,你会得到一个T或T的子类。

超级

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

List<?super Integer> foo3表示这些都是合法的赋值:

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

Reading - Given the above possible assignments, what type of object are you guaranteed to receive when you read from List foo3: You aren't guaranteed an Integer because foo3 could be pointing at a List<Number> or List<Object>. You aren't guaranteed a Number because foo3 could be pointing at a List<Object>. The only guarantee is that you will get an instance of an Object or subclass of Object (but you don't know what subclass). 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: You can add an Integer because an Integer is allowed in any of above lists. You can add an instance of a subclass of Integer because an instance of a subclass of Integer is allowed in any of the above lists. You can't add a Double because foo3 could be pointing at an ArrayList<Integer>. You can't add a Number because foo3 could be pointing at an ArrayList<Integer>. You can't add an Object because foo3 could be pointing at an ArrayList<Integer>.

PECS

记住PECS:“生产者延伸,消费者至上”。

"Producer Extends" - If you need a List to produce T values (you want to read Ts from the list), you need to declare it with ? extends T, e.g. List<? extends Integer>. But you cannot add to this list. "Consumer Super" - If you need a List to consume T values (you want to write Ts into the list), you need to declare it with ? super T, e.g. List<? super Integer>. But there are no guarantees what type of object you may read from this list. If you need to both read from and write to a list, you need to declare it exactly with no wildcards, e.g. List<Integer>.

例子

请注意这个来自Java泛型常见问题解答的例子。注意源列表src(生产列表)如何使用extends,而目标列表dest(消费列表)如何使用super:

public class Collections { 
  public static <T> void copy(List<? super T> dest, List<? extends T> src) {
      for (int i = 0; i < src.size(); i++) 
        dest.set(i, src.get(i)); 
  } 
}

也看到 如何添加到List<?extends数字>数据结构?