泛型通配符理解

发布于 2021-08-13  30 次阅读


是不是可以理解为list1中放着People及其子类的引用,所以objectlist不能赋值给list1;

是不是可以理解为没有对象是最小的,所以list1中存放的引用无法向下转型,所以只能存null;

package com.apesblog.day_25;

import java.util.ArrayList;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {
        List<? extends People> list1;
        List<? super People> list2;
        List<Object> objectlist = new ArrayList<Object>();
        List<People> peoplelist = new ArrayList<People>();
        List<Student> studentlist = new ArrayList<Student>();

        list1 = objectlist;//报错
        list1 = peoplelist;
        list1 = studentlist;

        list2 = objectlist;
        list2 = peoplelist;
        list2 = studentlist;//报错

        list1.add(null);
        list1.add(new People());//报错
        list1.add(new Student());//报错

        list2.add(null);
        list2.add(new People());
        list2.add(new Student());
        list2.add(new Object());//报错

    }

}

class People {
}

class Student extends People {
}