Why is List <String> not a subtype of List <Object>?

Possible duplicate:
java generics covariance

I am trying to understand that List<String> is not a subtype of List<Object> .

In effective Java, Josh Bloch notes that while this may seem contradictory, it makes sense. The reason he stated is because you can put any object in a List<Object> , but you can only put a String in a List<String> . I'm not sure how this justifies why the list of strings is not a subtype of the list of objects.

Perhaps the term subtype confuses me. I think this means that when S is a subtype of T, an instance of S is an instance of T. Therefore, for a List<String> for a subtype of List<Object> Object, there must be a superclass of String, which is technically. Any idea when my reasoning went wrong?

+4
source share
2 answers
 List<String> s = new ArrayList<String>(); List<Object> o = s; o.add(new Object()); String first = s.get(0); // boom 
+11
source

This refers to what means that A is a subtype of B The official name for this is the Liskov signature principle , which says that A is a subtype of B if and only if you can take any valid program that has something like B , replace something like A , and that's it Equally will be a valid program. The effect of this is that if you can use A wherever you could use B , then A is a subtype of B

So, in this case, since this is part of the real (real "compilation" task):

 public static void doThing(List<Object> x) { x.add(new Object()); } 

Then, according to the Liskov signature principle, if List<String> was a subtype of List<Object> , this would also be part of a valid program:

 public static void doThing(List<String> y) { y.add(new Object()); } 

But it is clear that the second fragment cannot be compiled. Therefore, this second snippet is not part of the actual program; therefore, List<String> not a subtype of List<Object> .

Similarly, vice versa: it is also not a subtype of List<String> . List<Object> . Searching for a piece of the program to prove that this remains an exercise for the reader.

+4
source

Source: https://habr.com/ru/post/1400256/


All Articles