【问题标题】:What is a difference between <? super E> and <? extends E>?< 和有什么区别?超级 E> 和 <?扩展 E>?
【发布时间】:2010-11-24 23:40:54
【问题描述】:

&lt;? super E&gt;&lt;? extends E&gt; 有什么区别?

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

public LinkedBlockingQueue(Collection<? extends E> c)

方法之一:

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

【问题讨论】:

    标签: java generics


    【解决方案1】:

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

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

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

    Parent extends Object
    Child extends Parent
    

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

    同样,您可以将该队列排入List&lt;Object&gt;,因为每个Parent 都是Object...但您不能将其排入List&lt;Child&gt;,因为List&lt;Child&gt; 期望它的所有元素都是兼容Child

    【讨论】:

    • +1。这确实是实际的区别。 extends 获取,super 插入。
    • @Jon 您在第一段中所说的(在这两种情况下 E 本身都可以。)是什么意思?
    • @Geek:我的意思是,如果你有 ? extends InputStream? super InputStream 之类的东西,那么你可以使用 InputStream 作为参数。
    • 我从来没有真正得到 Josh Block 在有效 Java 中的 PECS 解释。但是@Yishai,这是一种有用的记忆方式。或许我们可以提出一个新的助记词,SAGE:Super -> Add / Get -> Extend
    • 所以如果我没看错的话,“ extends E>”需要那个“?”是“E”的子类,而“”要求“E”是“?”的子类,对吧?
    【解决方案2】:

    您可能want to google for the terms 逆变 (&lt;? super E&gt;) 和协方差 (&lt;? extends E&gt;)。我发现理解泛型对我来说最有用的是理解Collection.addAll的方法签名:

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

    就像您希望能够将 String 添加到 List&lt;Object&gt; 一样:

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

    您还应该能够通过addAll 方法添加List&lt;String&gt;(或Strings 的任何集合):

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

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        &lt;? extends E&gt;E 定义为上限:“这可以转换为E”。

        &lt;? super E&gt;E 定义为下限:“E 可以转换为此。”

        【讨论】:

        • 这是我见过的最简单/实用的差异总结之一。
        • 几十年现在(使用 OOP)我一直在与“上”和“下”概念的本能倒置作斗争。加重!对我来说,Object 本质上是一个较低级别的类,尽管它是最终的超类(并且在 UML 或类似的继承树中垂直绘制)。尽管尝试了无数次,但我始终无法撤消此操作。
        • @tgm1024 “超类”和“子类”一定会给你带来很多麻烦。
        • @DavidMoles,为什么?你显然没有遵循我所说的。 “超类”类似于“超集”;专业化的概念是减少 IS-A 关系下的适用性。苹果是一种水果。 Fruit(超类)是包含 Apple(子类)作为子集的超集。这种语言关系很好。我要说的是“上”和“下”具有到“超集”和“子集”的内在映射的概念。 OO 中应避免使用 Upper 和 Lower 作为术语。
        • @tgm1024 "Super-" 来自拉丁文 super "above, on",而 "sub-" 来自拉丁文 sub "under , 下”。也就是说,从词源上来说,super是up,sub是down。
        【解决方案5】:

        我将尝试回答这个问题。但要获得真正好的答案,您应该查看 Joshua Bloch 的《Effective Java (2nd Edition)》一书。他描述了助记符 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/

        【讨论】:

          【解决方案6】:

          原因在于 Java 如何实现泛型。

          数组示例

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

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

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

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

          最后一行可以正常编译,但如果你运行这段代码,你会得到一个ArrayStoreException。因为你试图将一个双精度数放入一个整数数组中(无论是通过数字引用访问)。

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

          所以,如您所见,一件事是对象的实际类型,另一件事是您用来访问它的引用的类型,对吧?

          Java 泛型的问题

          现在,Java 泛型类型的问题是类型信息被编译器丢弃,并且在运行时不可用。这个过程称为type erasure。在 Java 中实现这样的泛型是有充分理由的,但这是一个很长的故事,除其他外,它必须与预先存在的代码兼容(请参阅How we got the generics we have)。

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

          例如,

          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); 
          

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

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

          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。

          Get/Put 原则

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

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

          public static void copy(List<? extends Number> source, List<? super Number> target) {
              for(Number number : source) {
                  target.add(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);
          

          【讨论】:

          • 这个答案应该会顶到顶部。很好的解释。
          • @edwindalorzo,您想在逆变器下修正一个小错字。你说List&lt;Object&gt; myObjs = new List&lt;Object();(第二个Object缺少结束&gt;)。
          • 这些微妙概念的精彩、简单和清晰的例子!
          • 你可以添加一些东西来帮助别人记住事情。当你想从一个超类调用一个方法时,你使用super.methodName。当使用&lt;? super E&gt; 时,它的意思是“super 方向上的东西”,而不是extends 方向上的东西。示例:Object 位于Numbersuper 方向(因为它是超类),Integer 位于extends 方向(因为它扩展了Number)。
          【解决方案7】:

          在回答之前;请明确

          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);      
          
          
                      } 
              }
          
              }
          }
          

          【讨论】:

          【解决方案8】:

          &lt;? super E&gt; 表示any object including E that is parent of E

          &lt;? extends E&gt; 表示any object including E that is child of E .

          【讨论】:

          • 简短而甜蜜的答案。
          • 根据您的第一个“解释”;List&lt;? super Parent&gt; list = new ArrayList&lt;&gt;(); list.add(new Child());(其中 ChildParent 的子类)这必须是无效的,但它可以编译并且是有效的
          【解决方案9】:

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

          【讨论】:

          • 我想知道这个答案是如何得到支持的。无法将任何类型的任何元素放入定义为&lt;? extends Parent&gt; 的列表中。学习的人很多,请不要为了回答而误导他们
          【解决方案10】:

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

          扩展:列表 extends T> 'extend' 保证集合中的对象 READ 是 T 类型。

          解释

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

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

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

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

          ' super T>' 确保-

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

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

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

          ' extends T>' 确保-

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

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

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

          考虑类层次结构

          类基{}

          类中间扩展基{}

          第三层类扩展中级{}

          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
          }
          

          【讨论】:

            猜你喜欢
            • 2010-12-26
            • 1970-01-01
            • 1970-01-01
            • 2013-06-12
            • 1970-01-01
            • 2011-02-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多