3

I'm really having trouble understanding at an intuitive level why the following causes a compile time error.

Collection<String> c1 = new ArrayList<>();
Collection<Object> c2 = c1;

I understand that the second statement above is illegal but I can't wrap my head around it. String is an Object but a Collection of strings is not a collection of objects ? What makes this illegal ? Everywhere I read the tutorials simply state that the inheritance relationship does not hold when dealing with generic collections but don't offer much explanation as to why.

Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66
  • 1
    http://stackoverflow.com/questions/18666710/why-are-arrays-covariant-but-generics-are-invariant ? –  Apr 06 '17 at 17:35
  • 3
    If the next line of code is `c2.add(Integer.valueOf(5));`, what happens when someone relies on `c1` containing only Strings? – VGR Apr 06 '17 at 17:36
  • 3
    Because a `Collection` can do things that `Collection` can't do, for example hold integers. Thus `Collection` cannot be a subtype of `Collection`. – RaminS Apr 06 '17 at 17:36
  • It's not about the actual objects in the list; obviously you can have a Collection that is full of Strings. It's about what type you can know the objects coming out of the list must be, the Collection enforces only that objects put in it are instances of Object. – Nathan Hughes Apr 06 '17 at 17:38
  • Consider checking [covariance](https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)) in java; [(example here)](http://stackoverflow.com/questions/2660827/java-generics-covariance). – Menelaos Kotsollaris Apr 06 '17 at 17:39

0 Answers0