Java中<?>,<? extends E>,<? super E>
阅读原文时间:2023年07月08日阅读:1

  在集合中,经常可看到,它们都是属于泛型;

  

   是泛型通配符,任意类型,如果没有明确,那么就是Object以及任意类型的Java类;

  

   向下限定,E及其子类,表示包括E在内的任何子类;

  

   向上限定,E及其父类,表示包括E在内的任何父类;

  示例如下:

class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

public class CollectionDemo {

    public static void main(String\[\] args) {  
        Collection<?> c1 = new ArrayList<Animal>();  
        Collection<?> c2 = new ArrayList<Dog>();  
        Collection<?> c3 = new ArrayList<Cat>();  
        Collection<?> c4 = new ArrayList<Object>();

        Collection<? extends Animal> c5 = new ArrayList<Animal>();  
        Collection<? extends Animal> c6 = new ArrayList<Dog>();  
        Collection<? extends Animal> c7 = new ArrayList<Cat>();  
        // Collection<? extends Animal> c8 = new ArrayList<Object>();

        Collection<? super Animal> c9 = new ArrayList<Animal>();  
        // Collection<? super Animal> c10 = new ArrayList<Dog>();  
        // Collection<? super Animal> c11 = new ArrayList<Cat>();  
        Collection<? super Animal> c12 = new ArrayList<Object>();  
    }

}

    在上述代码中,c1,c2,c3,c4中代表任意类型,c5,c6,c7中代表包括Animal在内的任何子类;而c8中,Object是所有类的基类,Animal是它的子类,只包含Animal及其子类,所以这里会编译报错;c9,c10,c11,c12中表示包含Animal及其父类,c10,c11这里会编译报错;