This questions is prompted by strange HashMap.put() behaviour
I think I understand why Map<K,V>.put takes a K but Map<K,V>.get takes an Object, it seems not doing so will break too much existing code.
Now we get into a very error-prone scenario:
java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>(); m.put(5L,'Five'); // compiler barfs on m.put(5, 'Five') m.contains(5); // no complains from compiler, but returns false
Couldn’t this have been solved by returning true if the Long value was withing int range and the values are equal?
Here is the source from Long.java
I.e. it needs to be a Long type to be equal. I think the key difference between:
and your example above is that with primitives an implicit widening of the int value can occur, however with object types there are no rules for implicitly converting from Integer to a Long.
Also check out Java Puzzlers, it has a lot of examples similar to this.