HashMap Method Signatures
Why does the put
method take as input key
a parameter of the K
type:
public V put(K key, V value)
And the get
method takes as input key
a parameter of the Object
type?
public V get(Object key)
I tried using the{[24] methods in my simplified implementation of HashMap
]}
public V get(K key)
public V put(K key, V value)
And it works, just like
public V get(Object key)
public V put(Object key, Object value)
As far as I understand, the put
method should accept exactly K key
and V value
, because the{[24] method is called in the body of this method]}
void addEntry(int hash, K key, V value, int bucketIndex)
And without an explicit type cast (addEntry(hash, (K) key, (V) value, i);
) call to this method would cause a compilation error if key
and value
were of type Object
. But why does the get
method take as input key
a parameter of the Object
type, and not K
? After all, it's somehow ugly, or something (different style)... and this should probably have some special meaning.
1 answers
The point is that the Map
specification does not require that all keys have the same type. It only requires the correct behavior of the equals
method (and hashCode
for HashMap
) for objects that are used as keys.
Of course, the implementation of the equals
method usually requires that the classes of the objects being compared match, among other things. But there are cases where there is a different behavior. For example, when comparing implementations java.util.List
(ArrayList
, LinkedList
etc.) all that is required is that the contents of these lists should be equivalent. For this reason, you can declare a variable with the type Map<ArrayList, String>
while passing a variable of the type LinkedList
to the get
method, and this will be quite a working option.
If you are wondering why to declare Map<ArrayList, String>
instead of Map<List, String>
, then I can give, although narrowly focused, but still an example. Imagine that your variable with the type Map<ArrayList, String>
is serialized periodically, and you really need the performance of the specified variable. serialization. Therefore, you explicitly require that the writable keys be of the specified type (I will not talk about the actual serialization speed ArrayList
right now). And when searching for a value object, you can pass any type of argument to the get
method, for example, the same LinkedList
, which will make your life a little easier.
P.S. You can certainly discuss this topic, but these are the realities of Java. It's quite possible that this is a design flaw. And referring to this answer I can say that we tried to do something similar, but there were some difficulties, and this idea was abandoned.