Re: HashMap get/put
Stefan Ram wrote :
Setting with a wrong type can result in a Map that breaks
its contract. Therefore, it is forbidden. Getting with a
wrong type cannot do such harm, so, it is not forbidden.
After all, you can meaningfully and correctly detect at run
time that for a wrong key, there is no value in the map.
Wojtek wrote:
No it is not an error. Just will never retrieve ANY value if you use the
wrong type (see below).
This came about because I changed the key for a HashMap to one that is
more specific (such as String to MyKey). All the "put" statements were
caught. However ALL the get statements were not. I had to manually go
through the code to locate each occurrence and change it.
And of course I missed some and the code broke during runtime. I had
assumed that generics would solve this type of issue.
Generics only handle what is declared generically. 'Map#get()' is not so
declared. Assumptions based on falsehood will yield false conclusions.
<http://java.sun.com/javase/6/docs/api/java/util/Map.html#get(java.lang.Object)>
Caveat: Yes it is possible to get the same hashcode with two different
types, however it would be highly unlikely.
And this is relevant how? 'Map' retrieval is defined in terms of 'equals()',
not 'hashCode()'.
<http://java.sun.com/javase/6/docs/api/java/util/Map.html#get(java.lang.Object)>
... formally, if this map contains a mapping from a key k to a value v
such that (key==null ? k==null : key.equals(k)),
then this method returns v; otherwise it returns null.
(There can be at most one such mapping.)
FWIW, if 'Map#get()' had been redefined generically, it would have broken
existing code without providing an improvement. Code that would have not
gotten a value still does not get a value without introducing a new error.
Maybe they erred in this, but they were trying to maintain backward compatibility.
It's a shame that the compiler didn't find your refactoring mistake for you,
but it was your mistake, not Java's.
--
Lew