6

I've been told by several people that Java allows covariant array subtyping in other words if A is a subtype of B, then A[] is a subtype of B[], but that this is a bad feature because it can lead to runtime errors. Can someone give me a concrete example to illustrate how it causes runtime errors and if/how does Java address this problem?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
user98289
  • 139
  • 9
  • 5
    Java addresses the problem **by** causing runtime errors. – Sotirios Delimanolis Feb 17 '15 at 20:53
  • Is that really it? Wow, I was hoping that there would be a better mechanism to limit this from happening. Out of curiosity what would you guys do to fix this problem (besides simple avoid it :) )? – user98289 Feb 17 '15 at 20:56
  • @user98289 there is. Scala solves it by enforcing correct usage of covariance and contravariance [in the compiler](http://blogs.atlassian.com/2013/01/covariance-and-contravariance-in-scala/). – Boris the Spider Feb 17 '15 at 20:57

1 Answers1

6

Very simple.

String strings[] = {"Broken","Type", "system"};
Object objects[] = strings;

objects[0] = 5; // compiles fine, but throws ArrayStoreException at runtime

Covariant types are not bad as long as you as you take things out, but the moment you put things in, the whole thing breaks. Imagine you have a method takes an Object[] as a parameter.

fn(Object[]a){
...   
}

wouldn't it be nice to be able to call it with a String[]?

 String[] s = {"I","didn't","know","that","this","was","broken"}
 fn(s);

Well, it sounds natural to be able to do so, especially in the early days when we didn't have generics in the language. And all this works fine as long as nothing get mutated, and Java doesn't provide any mechanism to guarantee that.

You should always favour Lists over arrays, because Lists use generics which are invariant.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77