Why is List not a sub-type of List<Object>?

后端 未结 6 1479
你的背包
你的背包 2020-12-10 05:43
public void wahey(List list) {}

wahey(new LinkedList());


The call to the method will not type-check. I can\'t even cas

6条回答
  •  旧时难觅i
    2020-12-10 06:35

    Consider if it was...

    List nums = new ArrayList();
    List objs = nums
    objs.add("Oh no!");
    int x = nums.get(0); //throws ClassCastException
    
    
    

    You would be able to add anything of the parent type to the list, which may not be what it was formerly declared as, which as the above example demonstrates, causes all sorts of problems. Thus, it is not allowed.

    提交回复
    热议问题