What is the difference between List and List<? extends Number>?

后端 未结 3 2140
野的像风
野的像风 2020-12-03 15:28

I have a very basic question ragarding Java generics . I thought that both List and List are

3条回答
  •  爱一瞬间的悲伤
    2020-12-03 15:57

    Generic types are more pedantic.

    means Number or an unknown a sub class. If you obtain such a value it will be a Number, but you cannot give a value of this type because you don't know which is valid.

    The difference is in arguments and return values.

    List numbers = new ArrayList();
    Number n = 1;
    numbers.add(n); // ok.
    n = numbers.get(0); // ok
    numbers.add(1); // ok.
    
    List numbers2 = new ArrayList();
    numbers2.add(n); // not ok
    n = numbers2.get(0); // ok
    
    List numbers3 = new ArrayList();
    numbers3.add(n); // ok
    n = numbers3.get(0); // not ok.
    

    super is used in a few places to signify the type can be a super type. e.g.

    In Collections, this method says the Comparator needs to be able to compare the same type or any super type.

    public static  void sort(List list, Comparator c)
    

    This means you can have

    Comparator comparesAnyNumbers = ...
    List ints = ...
    Collections.sort(ints, comparesAnyNumbers);
    

提交回复
热议问题