Demystify Wildcard for me

Why am I getting a compile-time error on this piece of code?

public Interface Location { ....... } 

Class Code ...

  Map<Type, List<? extends Location>> locationsTypeMap = new HashMap<Type, List<? extends Location>>(); /** Code to add elements to the hashMap. */ newLocation = getNewLocation() while(mapHasElements){ Location.Type key = location.getType(); List<? extends Location> valueList = (List<? extends Location>)locationsTypeMap.get(key); //1 valueList.add(newLocation);/*Compile error*/ } 

On the other hand, if I replace step 1 with the line below, it works

 List<Location> valueList = (List<Location>)locationsTypeMap.get(key); 
+3
java generics wildcard
Jan 07 '10 at
source share
3 answers

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 .

+8
Jan 07 '10 at 23:45
source share

SO members have demystified this exact case before for me. Although you accepted the answer, you can still check this:

Why is subclassing a restricted wildcard allowed only in certain places?

+2
Jan 07
source share

Its type is with null type:

http://msdn.microsoft.com/en-us/library/1t3y8s4s%28VS.80%29.aspx

EDIT: I have to be wrong, given the two answers above! Sorry!

-one
Jan 07 '10 at 23:48
source share



All Articles