简体   繁体   中英

about generics strange behavior for me

take the following code:

 public class Main {

    public static void main(String[] args) {
        List<Object> list1 = new ArrayList<Object>();
        List<? super Integer> list2 = list1;
        list2.add(1);
        list1.add("two");
        //list2.add("three"); // will never compile!!.
        System.out.println("list1:  " + list1.toString());
        System.out.println("list2:  " + list2.toString());

    }

}

here is the output:

list1:  [1, two]
list2:  [1, two]

on the one hand, list2 doesn't allow the add() method on objects like the String "three"; but on the other hand it references a List containing Objects.

The compiler doesn't care what kind of objects the list instance accepts. At byte code level any reference is accepted because of type erasure. It just knows about two variables with a List type parameterized with a particular generic type. That one of these variables is assignable to the other is something that is checked and then forgotten.

So when you try to add "three" it looks at the generic type that is accepted by the type of list2 , sees it doesn't match, and throws a compile error.

As for the program: there isn't any problem. If you want to restrict the objects you want to add or remove from the list through a variable reference then that is up to you.

Note that it is impossible to retrieve a String from the list referenced by the variables without a cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM