In the last paragraph of Item 25 in the Effective Java (2nd), it's said:
Arrays and generics have very different type rules. Arrays are covariant and reified; generics are invariant and erased.
Could someone give better definitions of the bolded terms in relation to arrays and generics in Java? I wouldn't mind some examples either.
You didn't mention if you were confused about a particular concept, so I'm going to try to just give basic definitions of covariance and invariance.
Covariance preserves type ordering, invariance does not. What this means is that sub-typing is or isn't preserved (inverted in the case of contravariance).
So, if you had the following class
and...
With covariant typing (e.g. arrays), the function
is perfectly valid used as
In other words, array types are exposed to the runtime or reified.
With invariant typing (e.g. generics), sub-typing isn't preserved. So, for example,
X<B>
would have no type relation toX<A>
other thanX
. This is partially a consequence of generic types not being exposed to the runtime or erased.However, you can still explicitly express covariance and contravariance in Java using
extends
andsuper
respectively. For example with the classThe function
would be valid used as