Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is java.util.Map.get(...) not generic? [duplicate]

Tags:

java

generics

map

Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic

This method and a number of other methods in the Map interface are not generic. Almost anywhere a key value is expected as a parameter, it accepts Object instead, namely remove, get and containsKey.

Any idea as to why they made this decision. My assumption is that it was done to support legacy code, but to me, I think that is a weak position.

Can anyone provide me a specific reason why it would be preferable to accept Object here instead of KeyType.

like image 970
Kevin Dolan Avatar asked Jan 13 '11 07:01

Kevin Dolan


People also ask

What happens if we give duplicate key in HashMap?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Can 2 keys have same value in map?

However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.

Can HashMap use generic types?

The term generic simply is the idea of allowing the type (Integer, Double, String, etc. or any user-defined type) to be the parameter to methods, class, or interface. For eg, all the inbuilt collections in java like ArrayList, HashSet, HashMap, etc. use generics.


1 Answers

The objects used to retrieve/remove/check for existance of a given key need not necessarily be of the same type as the object used to store it (= the key).

It needs to be equal and return the same hashCode as the key, but nothing in the spec says that it must be of the same type.

That fact is rarely used and most of the time you'll retrieve the values with the same keys (or at least objects of the same types) as the ones you use to store them.

But since that was a supported use case in the "old" HashMap, it needs to be supported in the generics version as well.

Note that all methods that keySet() uses the specific type, as it's sure to return exactly the objects used as keys when put() was called.

like image 117
Joachim Sauer Avatar answered Nov 15 '22 16:11

Joachim Sauer