泛型通配符

泛型通配符<?>:    

    任意类型,如果没有明确,那么就是Object以及任意的Java类了
    ? extends E:            向下限定,E及其子类
    ? super E:            向上限定,E及其父类
  
      

 /**
         * 泛型如果明确了数据类型以后,那么要求左右两边的数据类型必须一致
         */
        Collection<Object> col1 = new ArrayList<Object>() ;
        Collection<Object> col2 = new ArrayList<Animal>() ;//报错

        // ? 表示任意的数据类型
        Collection<?> col5 = new ArrayList<Object>() ;
        Collection<?> col6 = new ArrayList<Animal>() ;

        // ? extends E : 向下限定    , ? 表示的是E或者E的子类
//        Collection<? extends Animal> col9 = new ArrayList<Object>() ;//报错
        Collection<? extends Animal> col10 = new ArrayList<Animal>() ;
        Collection<? extends Animal> col11 = new ArrayList<Dog>() ;

        // ? super E:  向上限定 , ? 表示的是E或者E的父类
        Collection<? super Animal> col13 = new ArrayList<Object>() ;
        Collection<? super Animal> col14 = new ArrayList<Animal>() ;
//        Collection<? super Animal> col15 = new ArrayList<Dog>() ;//报错
    

猜你喜欢

转载自blog.csdn.net/qq_38454165/article/details/81362296