Java <? 之间有什么区别?超级 E> 和 <? 扩展 E>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1368166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:14:53  来源:igfitidea点击:

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

javagenerics

提问by Tomasz B?achowicz

What is the difference between <? super E>and <? extends E>?

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

For instance when you take a look at class java.util.concurrent.LinkedBlockingQueuethere is the following signature for the constructor:

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

public LinkedBlockingQueue(Collection<? extends E> c)

and for one for the method:

对于方法之一:

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

采纳答案by Jon Skeet

The first says that it's "some type which is an ancestor of E"; the second says that it's "some type which is a subclass of E". (In both cases E itself is okay.)

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

So the constructor uses the ? extends Eform so it guarantees that when it fetchesvalues from the collection, they will all be E or some subclass (i.e. it's compatible). The drainTomethod is trying to put values intothe collection, so the collection has to have an element type of Eor a superclass.

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

As an example, suppose you have a class hierarchy like this:

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

Parent extends Object
Child extends Parent

and a LinkedBlockingQueue<Parent>. You can construct this passing in a List<Child>which will copy all the elements safely, because every Childis a parent. You couldn't pass in a List<Object>because some elements might not be compatible with Parent.

和一个LinkedBlockingQueue<Parent>。您可以构造此传入 a List<Child>,它将安全地复制所有元素,因为 eachChild是父元素。您无法传入 aList<Object>因为某些元素可能与Parent.

Likewise you can drain that queue into a List<Object>because every Parentis an Object... but you couldn't drain it into a List<Child>because the List<Child>expects all its elements to be compatible with Child.

同样,您可以将该队列排入 a 中,List<Object>因为 everyParentObject... 但您不能将其排入 a 中,List<Child>因为List<Child>期望其所有元素都与Child.

回答by oxbow_lakes

You might want to google for the termscontravariance(<? super E>) and covariance(<? extends E>). I found that the most useful thing when comprehending generics was for me to understand the method signature of Collection.addAll:

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

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

Just as you'd want to be able to add a Stringto a List<Object>:

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

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

You should also be able to add a List<String>(or any collection of Strings) via the addAllmethod:

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

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

However you should realize that a List<Object>and a List<String>are not equivalent and nor is the latter a subclass of the former. What is needed is the concept of a covarianttype parameter - i.e. the <? extends T>bit.

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

Once you have this, it's simple to think of scenarios where you want contravariancealso (check the Comparableinterface).

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

回答by vinaynag

A wildcard with an upper bound looks like " ? extends Type " and stands for the family of all types that are subtypes of Type , type Type being included. Type is called the upper bound .

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

A wildcard with a lower bound looks like " ? super Type " and stands for the family of all types that are supertypes of Type , type Type being included. Type is called the lower bound .

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

回答by David Moles

<? extends E>defines Eas the upper bound: "This can be cast to E".

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

<? super E>defines Eas the lower bound: "Ecan be cast to this."

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

回答by codefinger

I'm going to try and answer this. But to get a really good answer you should check Joshua Bloch's book Effective Java (2nd Edition). He describes the mnemonic PECS, which stands for "Producer Extends, Consumer Super".

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

The idea is that if you code is consuming the generic values from the object then you should use extends. but if you are producing new values for the generic type you should use super.

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

So for example:

例如:

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

And

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

But really you should check out this book: http://java.sun.com/docs/books/effective/

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

回答by Edwin Dalorzo

The reasons for this are based on how Java implements generics.

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

An Arrays Example

数组示例

With arrays you can do this (arrays are covariant)

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

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

But, what would happen if you try to do this?

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

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

This last line would compile just fine, but if you run this code, you could get an ArrayStoreException. Because you're trying to put a double into an integer array (regardless of being accessed through a number reference).

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

This means that you can fool the compiler, but you cannot fool the runtime type system. And this is so because arrays are what we call reifiable types. This means that at runtime Java knows that this array was actually instantiated as an array of integers which simply happens to be accessed through a reference of type Number[].

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

So, as you can see, one thing is the actual type of the object, and another thing is the type of the reference that you use to access it, right?

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

The Problem with Java Generics

Java泛型的问题

Now, the problem with Java generic types is that the type information is discarded by the compiler and it is not available at run time. This process is called type erasure. There are good reason for implementing generics like this in Java, but that's a long story, and it has to do with binary compatibility with pre-existing code.

现在,Java 泛型类型的问题是类型信息被编译器丢弃,并且在运行时不可用。这个过程称为类型擦除。在 Java 中实现这样的泛型是有充分理由的,但这是一个很长的故事,它与与预先存在的代码的二进制兼容性有关。

But the important point here is that since, at runtime there is no type information, there is no way to ensure that we are not committing heap pollution.

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

For instance,

例如,

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

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

If the Java compiler does not stop you from doing this, the runtime type system cannot stop you either, because there is no way, at runtime, to determine that this list was supposed to be a list of integers only. The Java runtime would let you put whatever you want into this list, when it should only contain integers, because when it was created, it was declared as a list of integers.

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

As such, the designers of Java made sure that you cannot fool the compiler. If you cannot fool the compiler (as we can do with arrays) you cannot fool the runtime type system either.

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

As such, we say that generic types are non-reifiable.

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

Evidently, this would hamper polymorphism. Consider the following example:

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

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

Now you could use it like this:

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

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

But if you attempt to implement the same code with generic collections, you will not succeed:

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

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

You would get compiler erros if you try to...

如果您尝试...

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

The solution is to learn to use two powerful features of Java generics known as covariance and contravariance.

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

Covariance

协方差

With covariance you can read items from a structure, but you cannot write anything into it. All these are valid declarations.

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

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

And you can read from myNums:

你可以阅读myNums

Number n = myNums.get(0); 

Because you can be sure that whatever the actual list contains, it can be upcasted to a Number (after all anything that extends Number is a Number, right?)

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

However, you are not allowed to put anything into a covariant structure.

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

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

This would not be allowed, because Java cannot guarantee what is the actual type of the object in the generic structure. It can be anything that extends Number, but the compiler cannot be sure. So you can read, but not write.

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

Contravariance

逆变

With contravariance you can do the opposite. You can put things into a generic structure, but you cannot read out from it.

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

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

In this case, the actual nature of the object is a List of Objects, and through contravariance, you can put Numbers into it, basically because all numbers have Object as their common ancestor. As such, all Numbers are objects, and therefore this is valid.

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

However, you cannot safely read anything from this contravariant structure assuming that you will get a number.

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

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

As you can see, if the compiler allowed you to write this line, you would get a ClassCastException at runtime.

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

Get/Put Principle

获取/放置原则

As such, use covariance when you only intend to take generic values out of a structure, use contravariance when you only intend to put generic values into a structure and use the exact generic type when you intend to do both.

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

The best example I have is the following that copies any kind of numbers from one list into another list. It only getsitems from the source, and it only putsitems in the target.

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

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

Thanks to the powers of covariance and contravariance this works for a case like this:

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

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

回答by Kanagavelu Sugumar

Before the answer; Please be clear that

在回答之前;请清楚

  1. Generics only compile time feature to ensure TYPE_SAFETY, it wont b available during RUNTIME.
  2. Only a reference with Generics will force the type safety; if the reference don't declared with generics then it will work without type safty.
  1. 泛型仅编译时功能以确保 TYPE_SAFETY,它不会在 RUNTIME 期间可用。
  2. 只有带有泛型的引用才会强制类型安全;如果引用没有用泛型声明,那么它将在没有类型安全的情况下工作。

Example:

例子:

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

Hope this will help you to understand wildcard more clear.

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

//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(animalObject);
                animalList.add(animalObject);      


            } 
    }

    }
}

回答by M Sach

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

<? super E>方法 any object including E that is parent of E

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

<? extends E>方法 any object including E that is child of E .

回答by Crox

You have a Parent class and a Child class inherited from Parent class.The Parent Class is inherited from another class called GrandParent Class.So Order of inheritence is GrandParent > Parent > Child. Now, < ? extends Parent > - This accepts Parent class or either Child class < ? super Parent > - This accepts Parent class or either GrandParent class

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