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?
No.
First of all: a
HashMapand (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
HashMapis 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, theEntryclass has exactly one reference to the key (in the aptly nameskeyfield), so the key is stored only once.