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

后端 未结 6 1472
你的背包
你的背包 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条回答
  •  死守一世寂寞
    2020-12-10 06:20

    There are essentially two dimensions of abstraction here, the list abstraction and the abstraction of its contents. It's perfectly fine to vary along the list abstraction - to say, for instance, that it's a LinkedList or an ArrayList - but it's not fine to further restrict the contents, to say: This (list which holds objects) is a (linked list which holds only numbers). Because any reference that knows it as a (list which holds objects) understands, by the contract of its type, that it can hold any object.

    This is quite different from what you have done in the non-generics example code, where you've said: treat this String as if it were a Double. You are instead trying to say: treat this (list which holds only numbers) as a (list which holds anything). And it doesn't, and the compiler can detect it, so it doesn't let you get away with it.

提交回复
热议问题