繁体   English   中英

之间有什么区别<? super E>和<? extends E> ?

[英]What is a difference between <? super E> and <? extends E>?

<? super E>区别<? super E> <? super E><? extends E> <? extends E> ?

例如,当您查看类java.util.concurrent.LinkedBlockingQueue ,构造函数具有以下签名:

public LinkedBlockingQueue(Collection<? extends E> c)

对于方法之一:

public int drainTo(Collection<? super E> c)

第一个( <? super E> )说它是“某种类型,它是 E 的祖先(超类)”; 第二个( <? extends E> )说它是“某种类型,它是 E 的子类”。 (在这两种情况下,E 本身都可以。)

所以构造函数使用? extends E ? extends E形式,因此它保证当它从集合中获取值时,它们都是 E 或某个子类(即它是兼容的)。 drainTo方法试图将值放入集合中,因此集合必须具有E或超类的元素类型。

例如,假设您有一个这样的类层次结构:

Parent extends Object
Child extends Parent

和一个LinkedBlockingQueue<Parent> 您可以在List<Child>构造此传递,它将安全地复制所有元素,因为每个Child都是父级。 您无法传入List<Object>因为某些元素可能与Parent不兼容。

同样,您可以将该队列排入List<Object>因为每个Parent都是一个Object ...但您不能将其排入List<Child>因为List<Child>期望其所有元素都与Child兼容。

其原因基于 Java 如何实现泛型。

数组示例

使用数组你可以做到这一点(数组是协变的)

Integer[] myInts = {1,2,3,4};
Number[] myNumber = myInts;

但是,如果您尝试这样做会发生什么?

myNumber[0] = 3.14; //attempt of heap pollution

最后一行可以很好地编译,但是如果您运行此代码,您可能会得到一个ArrayStoreException 因为您试图将 double 放入整数数组中(无论是否通过数字引用访问)。

这意味着您可以欺骗编译器,但不能欺骗运行时类型系统。 之所以如此,是因为数组就是我们所说的可具体化的类型 这意味着在运行时 Java 知道这个数组实际上被实例化为一个整数数组,它恰好可以通过Number[]类型的引用访问。

所以,正如你所看到的,一件事是对象的实际类型,另一件事是你用来访问它的引用的类型,对吗?

Java泛型的问题

现在,Java 泛型类型的问题是类型信息被编译器丢弃,并且在运行时不可用。 这个过程称为类型擦除 在 Java 中实现这样的泛型是有充分理由的,但这是一个很长的故事,除其他外,它必须与预先存在的代码具有二进制兼容性(请参阅 我们如何获得我们拥有的泛型)。

但这里的重点是,由于在运行时没有类型信息,因此无法确保我们不会提交堆污染。

例如,

List<Integer> myInts = new ArrayList<Integer>();
myInts.add(1);
myInts.add(2);

List<Number> myNums = myInts; //compiler error
myNums.add(3.14); //heap pollution

如果 Java 编译器不阻止您执行此操作,则运行时类型系统也无法阻止您,因为在运行时无法确定此列表应该只是一个整数列表。 Java 运行时可以让你把任何你想要的东西放到这个列表中,当它应该只包含整数时,因为当它被创建时,它被声明为一个整数列表。

因此,Java 的设计者确保您不能欺骗编译器。 如果你不能欺骗编译器(就像我们可以用数组做的那样),你也不能欺骗运行时类型系统。

因此,我们说泛型类型是不可具体化的

显然,这会妨碍多态性。 考虑以下示例:

static long sum(Number[] numbers) {
   long summation = 0;
   for(Number number : numbers) {
      summation += number.longValue();
   }
   return summation;
}

现在你可以像这样使用它:

Integer[] myInts = {1,2,3,4,5};
Long[] myLongs = {1L, 2L, 3L, 4L, 5L};
Double[] myDoubles = {1.0, 2.0, 3.0, 4.0, 5.0};

System.out.println(sum(myInts));
System.out.println(sum(myLongs));
System.out.println(sum(myDoubles));

但是如果你试图用泛型集合实现相同的代码,你将不会成功:

static long sum(List<Number> numbers) {
   long summation = 0;
   for(Number number : numbers) {
      summation += number.longValue();
   }
   return summation;
}

如果您尝试...

List<Integer> myInts = asList(1,2,3,4,5);
List<Long> myLongs = asList(1L, 2L, 3L, 4L, 5L);
List<Double> myDoubles = asList(1.0, 2.0, 3.0, 4.0, 5.0);

System.out.println(sum(myInts)); //compiler error
System.out.println(sum(myLongs)); //compiler error
System.out.println(sum(myDoubles)); //compiler error

解决方案是学习使用 Java 泛型的两个强大功能,即协变和逆变。

协方差

使用协方差,您可以从结构中读取项目,但不能向其中写入任何内容。 所有这些都是有效的声明。

List<? extends Number> myNums = new ArrayList<Integer>();
List<? extends Number> myNums = new ArrayList<Float>();
List<? extends Number> myNums = new ArrayList<Double>();

您可以从myNums读取:

Number n = myNums.get(0); 

因为您可以确定无论实际列表包含什么,它都可以向上转换为数字(毕竟任何扩展数字的东西都是数字,对吗?)

但是,不允许将任何内容放入协变结构中。

myNumst.add(45L); //compiler error

这是不允许的,因为 Java 无法保证泛型结构中对象的实际类型是什么。 它可以是扩展 Number 的任何东西,但编译器无法确定。 所以你可以读,但不能写。

逆变

使用逆变你可以做相反的事情。 您可以将事物放入通用结构中,但无法从中读出。

List<Object> myObjs = new List<Object>();
myObjs.add("Luke");
myObjs.add("Obi-wan");

List<? super Number> myNums = myObjs;
myNums.add(10);
myNums.add(3.14);

在这种情况下,对象的实际性质是一个对象列表,通过逆变,可以将数字放入其中,基本上是因为所有数字都有对象作为它们的共同祖先。 因此,所有数字都是对象,因此这是有效的。

但是,假设您将获得一个数字,您无法安全地从这个逆变结构中读取任何内容。

Number myNum = myNums.get(0); //compiler-error

如您所见,如果编译器允许您编写此行,您将在运行时收到 ClassCastException。

获取/放置原则

因此,当您只打算从结构中取出泛型值时使用协变,仅打算将泛型值放入结构中时使用逆变,而当您打算同时执行这两种操作时使用确切的泛型类型。

我拥有的最好的例子是将任何类型的数字从一个列表复制到另一个列表中。 它仅从源中获取项目,并且仅项目放入目标中。

public static void copy(List<? extends Number> source, List<? super Number> target) {
    for(Number number : source) {
        target(number);
    }
}

由于协变和逆变的力量,这适用于这样的情况:

List<Integer> myInts = asList(1,2,3,4);
List<Double> myDoubles = asList(3.14, 6.28);
List<Object> myObjs = new ArrayList<Object>();

copy(myInts, myObjs);
copy(myDoubles, myObjs);

<? extends E> <? extends E>E定义为上限:“这可以强制转换为E ”。

<? super E> <? super E>E定义为下界:“ E可以转换为 this。”

<? super E> <? super E>表示any object including E that is parent of E

<? extends E> <? extends E>表示any object including E that is child of E .

我将尝试回答这个问题。 但是要获得真正好的答案,您应该查看 Joshua Bloch 的 Effective Java(第 2 版)一书。 他描述了助记符 PECS,它代表“生产者扩展,消费者超级”。

这个想法是,如果您的代码正在使用来自对象的通用值,那么您应该使用扩展。 但是如果你为泛型类型生成新值,你应该使用 super。

例如:

public void pushAll(Iterable<? extends E> src) {
  for (E e: src) 
    push(e);
}

public void popAll(Collection<? super E> dst) {
  while (!isEmpty())
    dst.add(pop())
}

但你真的应该看看这本书: http : //java.sun.com/docs/books/effective/

您可能想用谷歌搜索术语逆变<? super E> )和协方差<? extends E> )。 我发现在理解泛型时最有用的是让我理解Collection.addAll的方法签名:

public interface Collection<T> {
    public boolean addAll(Collection<? extends T> c);
}

就像您希望能够将String添加到List<Object>

List<Object> lo = ...
lo.add("Hello")

您还应该能够通过addAll方法添加List<String> (或任何String集合):

List<String> ls = ...
lo.addAll(ls)

但是,您应该意识到List<Object>List<String>不是等价的,后者也不是前者的子类。 需要的是协变类型参数的概念——即<? extends T> <? extends T>位。

一旦你有了这个,很容易想到你想要逆变的场景(检查Comparable接口)。

在回答之前; 请清楚

  1. 泛型仅编译时功能以确保 TYPE_SAFETY,它不会在 RUNTIME 期间可用。
  2. 只有带有泛型的引用才会强制类型安全; 如果引用没有用泛型声明,那么它将在没有类型安全的情况下工作。

例子:

List stringList = new ArrayList<String>();
stringList.add(new Integer(10)); // will be successful.

希望这能帮助您更清楚地理解通配符。

//NOTE CE - Compilation Error
//      4 - For

class A {}

class B extends A {}

public class Test {

    public static void main(String args[]) {

        A aObj = new A();
        B bObj = new B();
        
        //We can add object of same type (A) or its subType is legal
        List<A> list_A = new ArrayList<A>();
        list_A.add(aObj);
        list_A.add(bObj); // A aObj = new B(); //Valid
        //list_A.add(new String()); Compilation error (CE);
        //can't add other type   A aObj != new String();
         
        
        //We can add object of same type (B) or its subType is legal
        List<B> list_B = new ArrayList<B>();
        //list_B.add(aObj); CE; can't add super type obj to subclass reference
        //Above is wrong similar like B bObj = new A(); which is wrong
        list_B.add(bObj);
        
        

        //Wild card (?) must only come for the reference (left side)
        //Both the below are wrong;   
        //List<? super A> wildCard_Wrongly_Used = new ArrayList<? super A>();
        //List<? extends A> wildCard_Wrongly_Used = new ArrayList<? extends A>();
        
        
        //Both <? extends A>; and <? super A> reference will accept = new ArrayList<A>
        List<? super A> list_4__A_AND_SuperClass_A = new ArrayList<A>();
                        list_4__A_AND_SuperClass_A = new ArrayList<Object>();
                      //list_4_A_AND_SuperClass_A = new ArrayList<B>(); CE B is SubClass of A
                      //list_4_A_AND_SuperClass_A = new ArrayList<String>(); CE String is not super of A  


        List<? extends A> list_4__A_AND_SubClass_A = new ArrayList<A>();
                          list_4__A_AND_SubClass_A = new ArrayList<B>();
                        //list_4__A_AND_SubClass_A = new ArrayList<Object>(); CE Object is SuperClass of A
                          
                          
        //CE; super reference, only accepts list of A or its super classes.
        //List<? super A> list_4__A_AND_SuperClass_A = new ArrayList<String>(); 
                          
        //CE; extends reference, only accepts list of A or its sub classes.
        //List<? extends A> list_4__A_AND_SubClass_A = new ArrayList<Object>();
                          
        //With super keyword we can use the same reference to add objects
        //Any sub class object can be assigned to super class reference (A)                  
        list_4__A_AND_SuperClass_A.add(aObj);
        list_4__A_AND_SuperClass_A.add(bObj); // A aObj = new B();
        //list_4__A_AND_SuperClass_A.add(new Object()); // A aObj != new Object(); 
        //list_4__A_AND_SuperClass_A.add(new String()); CE can't add other type
        
        //We can't put anything into "? extends" structure. 
        //list_4__A_AND_SubClass_A.add(aObj); compilation error
        //list_4__A_AND_SubClass_A.add(bObj); compilation error
        //list_4__A_AND_SubClass_A.add("");   compilation error
    
        //The Reason is below        
        //List<Apple> apples = new ArrayList<Apple>();
        //List<? extends Fruit> fruits = apples;
        //fruits.add(new Strawberry()); THIS IS WORNG :)
    
        //Use the ? extends wildcard if you need to retrieve object from a data structure.
        //Use the ? super wildcard if you need to put objects in a data structure.
        //If you need to do both things, don't use any wildcard.

        
        //Another Solution
        //We need a strong reference(without wild card) to add objects 
        list_A = (ArrayList<A>) list_4__A_AND_SubClass_A;
        list_A.add(aObj);
        list_A.add(bObj);
        
        list_B = (List<B>) list_4__A_AND_SubClass_A;
        //list_B.add(aObj); compilation error
        list_B.add(bObj);

        private Map<Class<? extends Animal>, List<? extends Animal>> animalListMap;

        public void registerAnimal(Class<? extends Animal> animalClass, Animal animalObject) {
    
            if (animalListMap.containsKey(animalClass)) {
                //Append to the existing List
                 /*    The ? extends Animal is a wildcard bounded by the Animal class. So animalListMap.get(animalObject);
                 could return a List<Donkey>, List<Mouse>, List<Pikachu>, assuming Donkey, Mouse, and Pikachu were all sub classes of Animal. 
                 However, with the wildcard, you are telling the compiler that you don't care what the actual type is as long as it is a sub type of Animal.      
                 */   
                //List<? extends Animal> animalList = animalListMap.get(animalObject);
                //animalList.add(animalObject);  //Compilation Error because of List<? extends Animal>
                List<Animal> animalList = animalListMap.get(animalClass);
                animalList.add(animalObject);      


            } 
    }

    }
}

带有上限的通配符看起来像“? extends Type”,代表所有类型的家族,它们是 Type 的子类型,类型 Type 被包括在内。 类型称为上限。

具有下限的通配符看起来像“? super Type”,代表所有类型的家族,这些类型是 Type 的超类型,类型 Type 被包括在内。 类型称为下界。

你有一个父类和一个从父类继承的子类。父类继承自另一个名为 GrandParent 类的类。所以继承顺序是 GrandParent > Parent > Child。 现在, < ? extends Parent > - 这接受父类或子类 < ? super Parent > - 接受 Parent 类或 GrandParent 类

超级:列表<? super T> 'super' 保证要添加到集合中的对象是 T 类型。

扩展:列表<? extends T> 'extend' 保证从集合中读取的对象是 T 类型。

说明

从类型安全的角度理解“超级”和“扩展”之间的区别时,需要考虑三件事。

1.分配:什么类型的集合可以分配给泛型引用。

2.添加: 什么类型可以添加到引用的集合中。

3.阅读:可以从引用的集合中读取什么类型

' <? 超级 T> ' 确保-

  1. 可以分配任何类型 T 或其超类的集合。

  2. 任何类型 T 或其子类的对象都可以添加到集合中,因为它总是会通过 T 的“是 A”测试。

  3. 不能保证从集合中读取的项目的类型,除非是“对象”类型。 它可以是任何类型 T 或其超类,其中包括类型“Object”。

' <? 扩展 T>'确保-

  1. 可以分配任何类型 T 或其子类的集合。

  2. 由于我们无法确定引用类型,因此无法添加任何对象。 (即使是 'T' 类型的对象也不能添加,因为泛型引用可能会分配给 'T' 子类型的集合)

  3. 从集合中读取的项目可以保证为“T”类型。

考虑类层次结构

类基础{}

类中间扩展 Base{}

第三层类扩展中级{}

public void testGenerics() {

    /**
     * super: List<? super T> super guarantees object to be ADDED to the collection
     * if of type T.
     * 
     * extends: List<? extends T> extend guarantees object READ from collection is
     * of type T
     * 
     * Super:- 
     * 
     * Assigning : You can assign collection of Type T or its super classes
     * including 'Object' class.
     * 
     * Adding: You can add objects of anything of Type T or of its subclasses, as we
     * are sure that the object of type T of its subclass always passes Is A test
     * for T. You can NOT add any object of superclass of T.
     * 
     * Reading: Always returns Object
     */

    /**
     * To a Collection of superclass of Intermediate we can assign Collection of
     * element of intermediate or its Parent Class including Object class.
     */
    List<? super Intermediate> lst = new ArrayList<Base>(); 
    lst = new ArrayList<Intermediate>();
    lst = new ArrayList<Object>();

    //Can not assign Collection of subtype
    lst = new ArrayList<ThirdLayer>(); //Error! 

    /** 
     * Elements of subtype of 'Intemediate' can be added as assigned collection is
     * guaranteed to be of type 'Intermediate
     */
    
    lst.add(new ThirdLayer()); 

    lst.add(new Intermediate()); 
    
    // Can not add any object of superclass of Intermediate
    lst.add(new Base()); //Error!

    Object o = lst.get(0);
    
    // Element fetched from collection can not inferred to be of type anything
    // but 'Object'.
    Intermediate thr = lst.get(0); //Error!

    /**
     * extends: List<? extends T> extend guarantees object read from collection is
     * of type T 
     * Assigning : You can assign collection of Type T or its subclasses.
     * 
     * Adding: You cannot add objects of anything of Type T or even objects of its
     * subclasses. This is because we can not be sure about the type of collection
     * assigned to the reference. 
     * 
     * Reading: Always returns object of type 'T'
     */
    
    // Can assign collection of class Intermediate or its subclasses.
    List<? extends Intermediate> lst1 = new ArrayList<ThirdLayer>();
    lst1 = new ArrayList<Base>(); //Error! can not assign super class collection
    
    /**
     *  No element can be added to the collection as we can not be sure of
     *  type of the collection. It can be collection of Class 'Intermediate'
     *  or collection of its subtype. For example if a reference happens to be 
     *  holding a list of class ThirdLayer, it should not be allowed to add an
     *  element of type Intermediate. Hence no addition is allowed including type
     *  'Intermediate'. 
     */
    
    lst1.add(new Base()); //Error!
    lst1.add(new ThirdLayer()); //Error!
    lst1.add(new Intermediate()); //Error!

    
    /**
     * Return type is always guaranteed to be of type 'Intermediate'. Even if the
     * collection hold by the reference is of subtype like 'ThirdLayer', it always
     * passes the 'IS A' test for 'Intermediate'
     */
    Intermediate elm = lst1.get(0); 

    /**
     * If you want a Collection to accept (aka to be allowed to add) elements of
     * type T or its subclasses; simply declare a reference of type T i.e. List<T>
     * myList;
     */

    List<Intermediate> lst3 = new ArrayList<Intermediate>();
    lst3 = new ArrayList<ThirdLayer>(); //Error!
    lst3 = new ArrayList<Base>(); //Error!

    lst3.add(new Intermediate()); 
    lst3.add(new ThirdLayer());  // Allowed as ThirdLayer passes 'IS A' for Intermediate
    lst3.add(new Base()); //Error! No guarantee for superclasses of Intermediate
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM