Re: generic oversight?



VisionSet wrote:
When they retro fit generics to Collection classes why didn't they change
methods like this

containsKey(Object key)


to

containsKey(K key)

I was in secure type safe heaven for a bit...

On the face of it, it doesn't look type unsafe, does it? I mean if you give me a HashMap with a String key and I look for an Integer in it, I just wont find any (unless it's a null reference, possibly).


If I take you Map<String,Void> and assign it to Map<?,Void>, that should work. I've forgotten the type of the key, but really is there any problem with me looking up a key in it? And in order to do that, your contains key needs to be more relaxed. Something like:

    boolean containsKey(? super K key); // NOT LEGAL

That's not legal. Although if it was, appropriate semantics could make it illegal to check whether a Map<String,Void> contains an Integer key. The nearest we can get to the above is:

    boolean containsKey(Object key);


TreeMap introduces complications because the Comparator/Comparable may throw a ClassCastException. If we wanted to check the comparator, then the Map interface would need to develop a third generic parameter, that would almost always be irrelevant. Alternatively, I guess TreeMaps could do a preliminary check, but unfortunately the never did so can't really if backward compatibility is to be maintained (and they don't have the K.class).


Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.