Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java Map<K, V> take an untyped parameter for the get and remove methods?

Tags:

java

generics

api

I ran into a bug in my code where I was using the wrong key to fetch something from a Java map that I believed was strongly typed using Java generics. When looking at the Map Javadocs, many of the methods, including get and remove, take an Object as the parameter instead of type K (for a Map defined as Map). Why is this? Is there a good reason or is it an API design flaw?

like image 802
Michael Bobick Avatar asked Nov 24 '10 16:11

Michael Bobick


People also ask

How do I remove an item from a map in Java?

HashMap remove() Method in Java HashMap. remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.

Does a HashMap get return a reference?

It returns a reference.

What this get key method returns in map?

The get() method returns a specified element from a Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.


2 Answers

I think this is for backwards compatibility with older versions of the Map interface. It's unfortunate that this is the case however as you're right, it would be much better if this took the correct type.

like image 76
Jim Avatar answered Oct 05 '22 06:10

Jim


Because the map will return a value if the object passed to the get method is equal to any key stored in the map. Equal does not mean that they have to be of the same type, but that the key's and the passed object's equal methods are implemented in such a way, that the different object types are mutually recognized as equal.

The same applies of course to the remove method.


Example of valid code, which would break (not compile) if the get method only allowed parameters of type K:

LinkedList<Number> k1 = new LinkedList<Number>();
k1.add(10);

ArrayList<Integer> k2 = new ArrayList<Integer>();
k2.add(10);

Map<LinkedList<Number>, String> map = new HashMap<LinkedList<Number>, String>();

map.put(k1, "foo");
System.out.println(map.get(k2));
like image 35
jarnbjo Avatar answered Oct 05 '22 05:10

jarnbjo