Java generics: List = new LinkedList>() is prohibited?

前端 未结 3 1588
迷失自我
迷失自我 2021-01-04 12:44

How come, in Java, I can write

List list = new LinkedList();

but not

List>          


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 13:13

    Consider what would happen if you could.

    List> list1 = new LinkedList>();
    List> list2 = list1; // this shouldn't be allowed, because of the below
    Container foo = new Container();
    foo.add("hi");
    list2.add(foo); // legal, because Container is a subtype of Container
    Container bar = list1.get(0);
    Double x = bar.get(0); // type error; it is actually a String object
                           // this indicates that type safety was violated
    

    However, using List> doesn't have this problem because you cannot put anything (except null) into a list of this type (because there is no type that is guaranteed to be a subtype of "? extends Container").

提交回复
热议问题