Java generics and subtyping

I am actually having trouble understanding intuitively why the following results in a compile time error.

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

      

I understand that the second statement above is illegal, but I cannot wrap it up around it. String is an object, but a collection of strings is not a collection of objects? What makes it illegal? Everywhere I've read the tutorials, I just point out that inheritance relationships don't hold when dealing with shared collections, but doesn't provide much explanation as to why.

+3


source to share





All Articles