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

后端 未结 6 1482
你的背包
你的背包 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:43

    They aren't subtypes of each other due how generics work. What you want is to declare your function like this:

    public void wahey(List list) {}
    

    Then it will accept a List of anything that extends Object. You can also do:

    public void wahey(List list) {}
    

    This will let you take in Lists of something that's a subclass of Number.

    I'd recommend you pick up a copy of "Java Generics and Collections" by Maurice Naftalin & Philip Wadler.

提交回复
热议问题