W
Wojtek
If I have the following:
HashMap<MyKey,MyValue> map = new HashMap<MyKey,MyValue>();
MyKey myKey = new MyKey();
Then I can put in a value by:
map.put(myKey, new MyValue() );
The compiler enforces the use of these two types.
However to do a get I can do the following and the compiler does not
complain:
map.get(myKey); // this is right
map.get(myKey.toString()); // this is wrong yet legal
map.get(new Long(20)); // this is wrong yet legal
All of these are legal according to the compiler. Why is it that the
compiler does not enforce type checking on the get()?
Or rather, why does the spec not say get(K key) instead of get(Object
o)
http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#get(java.lang.Object)
HashMap<MyKey,MyValue> map = new HashMap<MyKey,MyValue>();
MyKey myKey = new MyKey();
Then I can put in a value by:
map.put(myKey, new MyValue() );
The compiler enforces the use of these two types.
However to do a get I can do the following and the compiler does not
complain:
map.get(myKey); // this is right
map.get(myKey.toString()); // this is wrong yet legal
map.get(new Long(20)); // this is wrong yet legal
All of these are legal according to the compiler. Why is it that the
compiler does not enforce type checking on the get()?
Or rather, why does the spec not say get(K key) instead of get(Object
o)
http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#get(java.lang.Object)