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

Java <;之间有什么区别;?超级E>;以及<;?扩展E>;?,java,generics,Java,Generics,第一种说法是“某种类型是E的祖先”;第二种说法是“某种类型,是E的一个子类”。(在这两种情况下,E本身都可以。) 所以构造函数使用?扩展E表单,以确保当它从集合中获取值时,它们都是E或某个子类(即,它是兼容的)。drainTo方法试图将值放入集合中,因此集合必须具有E元素类型或超类 例如,假设您有这样一个类层次结构: Parent extends Object Child extends Parent Integer[] myInts = {1,2,3,4,5}; Long[] myLongs

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

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

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

Parent extends Object
Child extends Parent
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));
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);
和一个
链接的锁定队列
。您可以在
列表
中构造此传递,该列表将安全地复制所有元素,因为每个
子项
都是父项。无法传入
列表
,因为某些元素可能与
父项
不兼容


同样,您可以将该队列排入
列表
,因为每个
父级
都是
对象
。。。但是您不能将其排入
列表
,因为
列表
要求它的所有元素都与
子项
兼容您可以逆变
具有上界的通配符看起来像“.扩展类型”和表示所有类型的族,这些类型都是类型的子类型,其中包括类型类型。类型称为上限


带下限的通配符看起来像“?super Type”,代表所有类型的超类型族,其中包括类型Type。类型称为下限。

我将尝试回答这个问题。但要得到一个真正好的答案,你应该查阅Joshua Bloch的《有效Java》(第二版)他描述了PEC的助记功能,它代表“生产者延伸,消费者超级”

其思想是,如果您的代码正在使用来自对象的泛型值,那么您应该使用extends。但是,如果您正在为泛型类型生成新值,那么您应该使用super

例如:

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

public void pushAll(Iterable原因基于Java实现泛型的方式

阵列示例

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

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

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
现在您可以这样使用它:

Parent extends Object
Child extends Parent
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));
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);
但是,如果尝试用泛型集合实现相同的代码,则不会成功:

static long sum(List<Number> numbers) {
   long summation = 0;
   for(Number number : numbers) {
      summation += number.longValue();
   }
   return summation;
}
因为您可以确定,无论实际列表包含什么,都可以将其升级为一个数字(毕竟扩展数字的任何东西都是一个数字,对吗?)

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

myNumst.add(45L); //compiler error
这是不允许的,因为Java不能保证泛型结构中对象的实际类型。它可以是任何扩展数字的东西,但编译器不能确定。所以您可以读取,但不能写入

对冲

相反,你可以做相反的事情。你可以把东西放到一个通用结构中,但你不能从中读出

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);
如您所见,如果编译器允许您编写这一行,您将在运行时得到ClassCastException

获取/放置原则

因此,当您仅打算从结构中提取泛型值时,请使用协方差;当您仅打算将泛型值放入结构中时,请使用逆变;当您打算同时执行这两项操作时,请使用确切的泛型类型

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

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

publicstaticvoidcopy(列表在答案之前;请明确

  • 泛型只有编译时特性才能确保类型_的安全性,它在运行时不可用
  • 只有带有泛型的引用才会强制执行类型安全;如果引用没有使用泛型声明,那么它将在没有类型安全的情况下工作。
  • 例如:

    List stringList = new ArrayList<String>();
    stringList.add(new Integer(10)); // will be successful.
    
    List-stringList=new-ArrayList();
    stringList.add(新整数(10));//将成功。
    
    希望这将帮助您更清楚地理解通配符。

    //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);      
    
    
                } 
        }
    
        }
    }
    
    //注意CE-编译错误
    //4-为
    A类{}
    类B扩展了{}
    公开课考试{
    公共静态void main(字符串参数[]){
    A aObj=新的A();
    B bObj=新的B();
    //我们可以添加相同类型(A)的对象或其子类型是合法的
    List_A=新的ArrayList();
    名单_
    
    List<? extends Number> myNums = new ArrayList<Integer>();
    List<? extends Number> myNums = new ArrayList<Float>();
    List<? extends Number> myNums = new ArrayList<Double>();
    
    Number n = myNums.get(0); 
    
    myNumst.add(45L); //compiler error
    
    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
    
    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);
    
    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);      
    
    
                } 
        }
    
        }
    }