Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "key" stored twice in Java HashMap?

Tags:

java

hashmap

When a Key-Value pair is added to a HashMap in Java, in order to determine the bucket location for value object, the hash map implementation uses hashCode of "key" object and applies hashing to it. And finally the key value pair is stored in the bucket. The key object is stored so that in case of collisions the object can be retrieved correctly.

My question is, is "key" object stored twice in HashMap, once as a key and then in the bucket where key -value pair is stored in a Linked List?

like image 371
user325643 Avatar asked Mar 14 '26 17:03

user325643


2 Answers

No.

First of all: a HashMap and (anything else in fact) can only ever store a reference to some object you pass into it. So even if it were to store two references to the key, the memory requirement for that would be minimal.

Next: the actual implementation of HashMap is not prescribed by the Java standard, so it may (and will) vary depending on which JVM you use.

And finally, looking at the OpenJDK source code of HashMap, the Entry class has exactly one reference to the key (in the aptly names key field), so the key is stored only once.

like image 69
Joachim Sauer Avatar answered Mar 17 '26 05:03

Joachim Sauer


No. To select the correct bucket, the key is hashed, and then this is used as an index. No need to store anything here.

like image 40
Oliver Charlesworth Avatar answered Mar 17 '26 05:03

Oliver Charlesworth