Skip to content

Instantly share code, notes, and snippets.

@thieux
Last active January 2, 2017 08:48
Show Gist options
  • Save thieux/8512b0447fc2f23e3d5138e73908f1ae to your computer and use it in GitHub Desktop.
Save thieux/8512b0447fc2f23e3d5138e73908f1ae to your computer and use it in GitHub Desktop.
How Java array covariance is bad
import org.junit.Test;
public class ArrayCovarianceTest {
@Test(expected = ArrayStoreException.class)
public void cat_should_not_be_set_in_dog_list() {
Animal[] animals = new Dog[1]; // array covariance
// Java compiler allows the assignment because Dog extends Animal
// But the Java runtime throws a "java.lang.ArrayStoreException: Cat"
animals[0] = new Cat();
}
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment