Why are arrays covariant but generics are invariant?

前端 未结 9 1467
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:44

From Effective Java by Joshua Bloch,

  1. Arrays differ from generic type in two important ways. First arrays are covariant. Generics are invariant.
  2. Cov

9条回答
  •  萌比男神i
    2020-11-22 01:04

    Generics are invariant: from JSL 4.10:

    ...Subtyping does not extend through generic types: T <: U does not imply that C <: C ...

    and a few lines further, JLS also explains that
    Arrays are covariant (first bullet):

    4.10.3 Subtyping among Array Types

    enter image description here

提交回复
热议问题