Java's wildcard

1, Tsuhaifu

Uncertain elements of the collection of specific data types
? Representing all types of

formats:

public void test(List<?> list){
    System.out.println(list);
}

2, limited wildcard

public class Test2 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        Dd d = new Dd();
        d.test(list);
        
        List<D1> ld = new ArrayList<D1>();
        d.test1(ld);
        List<A1> la = new ArrayList<A1>();
//      d.test1(la);//不能传A1对象类型,只能传C1及其子类
        
//      d.test2(ld);//不能传D1对象类型,只能传C1及其父类
        
        //接口
        List<Ee> le = new ArrayList<Ee>();
        d.test3(le);
    }
}

class Dd{
    /**
     * 不确定集合中的元素具体的数据类型
     * 使用?表示所有类型
     * @param list
     */
    public void test(List<?>list) {}//test方法需要一个list集合的参数,不确定list集合到底是存的数据的类型是什么?用?
    public void test1(List<? extends C1> list) {}//? extends C1 只允许接收C1或C1的子类
    public void test2(List<? super C1> list) {}//? super C1 只允许接收C1或C1的父类
    public void test3(List<? extends E1> list) {}//? extends E1 只允许接收接口E1的实现类
}

class A1{}
class B3 extends A1{}
class C1 extends B3{}
class D1 extends C1{}
//接口
interface E1{}
class Ee implements E1{}

Guess you like

Origin www.cnblogs.com/istart/p/12041129.html