What is the difference between and ?

后端 未结 2 1509
独厮守ぢ
独厮守ぢ 2020-11-28 06:30

What is the difference between this method declaration:

public static  List process(List nums){

a

2条回答
  •  悲哀的现实
    2020-11-28 07:17

    The first allows process of a List, a List, etc. The second doesn't.

    Generics in Java are invariant. They're not covariant like arrays.

    That is, in Java, Double[] is a subtype of Number[], but a List is NOT a subtype of List. A List, however, is a List.

    There are good reasons for generics being invariant, but that's also why the extends and super type are often necessary for subtyping flexibility.

    See also

    • Java Tutorials/Generics/Subtyping
      • Explains why generics invariance is a good thing
    • More fun with wildcards
      • Explains some uses of super and extends for bounded wildcards
    • Java Generics: What is PECS?
      • This discusses the "Producer extends Consumer super" principle
      • Effective Java 2nd Edition, Item 28: Use bounded wildcards to increase API flexibility

提交回复
热议问题