泛型 ? extends E ? super E的区别

package cn.itcast.generic;

import java.util.ArrayList;
import java.util.Collection;

public class SupperGenericDemo {

public static void main(String[] args) {
// 泛型如果明确写的时候,前后必须一致 ,c2,c3,c4会报错
Collection<Object> c1 = new ArrayList<Object>();
// Collection<Object> c2 = new ArrayList<Animal>();
// Collection<Object> c3 = new ArrayList<Cat>();
// Collection<Object> c4 = new ArrayList<Dog>();

// ?表示任意的类型都是可以的
Collection<?> c5 = new ArrayList<Object>();
Collection<?> c6 = new ArrayList<Animal>();
Collection<?> c7 = new ArrayList<Cat>();
Collection<?> c8 = new ArrayList<Dog>();

// ? extends E: 向下限定,E及其子类
// Collection<? extends Animal> c9 = new ArrayList<Object>();
Collection<? extends Animal> c10 = new ArrayList<Animal>();
Collection<? extends Animal> c11 = new ArrayList<Cat>();
Collection<? extends Animal> c12 = new ArrayList<Dog>();


// ? super E: 向上限定,E及其父类
Collection<? super Cat> c13 = new ArrayList<Object>();
Collection<? super Cat> c14 = new ArrayList<Animal>();
Collection<? super Cat> c15 = new ArrayList<Cat>();
// Collection<? super Cat> c16 = new ArrayList<Dog>();

}

}

class Animal{
}

class Cat extends Animal{
}

class Dog extends Animal{
}

posted @ 2022-12-20 09:33  luorx  阅读(24)  评论(0编辑  收藏  举报