Array Covariance in Java

In the early versions of Java, the collection library did not appear yet, and the type variant of the container type was also reflected in the Java array. Without type variants, even a simple method like sort() is hard to write in an efficient way:

Arrays.sort(Object[] a);

For this reason, Java arrays can be covariant - although doing so exposes static type systems to flaws, it is still necessary in the early stages of the Java platform:

  // This is completely legal
  String[] words = {"Hello World!"};
  Object[] objects = words;
  // Oh, my god, runtime error
  Objects[0] = new Integer(42);

Recent research on modern open source projects has shown that array covariation is rarely used and can almost be judged as a design flaw in programming languages. Therefore, you should avoid using array covariations when writing new code.

Comments