10th Jun 2009

Covariance in Arrays

The following code throws an ArrayTypeMismatchException.

Covariance in Arrays

I was never aware of this until today. Here is the reason for this behaviour.

On a related note, Generics catches this problem at compile time.

Click here to get code that you can copy-paste.

One Response to “Covariance in Arrays”

  1. Binil Thomas Says:

    Yeah, as Eric mentions this is a problem in Java too. But I can understand why the original Java developers might have done it this way. If arrays were invariant on their type parameter, the compiler would not let you pass in a Derived[] instance to a method which expects a Base[].

Leave a Reply