The wildcard "? Extends Location" means "I want it to be List<T> for some T , where T is a subclass of Location (or is Location itself)."
Now leave it on one side for a second. You expect this to compile:
List<String> strings = new List<String>(); strings.add(new Object());
? I wouldnโt think so - you cannot add a bare โobjectโ to the list of strings. Any item in a list of strings must be a string.
Return to your first. Suppose locationsTypeMap.get(key) returns an object that is (logically ignore type erasure for now) a List<ExoticLocation> , but suppose newLocation is actually an instance of BoringLocation . You cannot add BoringLocation to the List<ExoticLocation> , and the compiler knows this, so it stops it.
All that you get from List<? extends Location> List<? extends Location> is guaranteed as Location , but you cannot add anything to it. The converse is true with super : you cannot guarantee that everything you get from List<? super Location> List<? super Location> will be Location , but you can add Location to it.
To give a completely different example: is it a bunch of bananas - a collection of fruits? Well, that is in a way - all you get from him is the fruit. But this is not different, because you cannot add any old kind of fruit to it - if you try to add an apple, it will fall :)
For more information, see Java Generics Angelika Langer Java Frequently Asked Questions .
Jon Skeet Jan 07 '10 at 23:45 2010-01-07 23:45
source share