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 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.
No. To select the correct bucket, the key is hashed, and then this is used as an index. No need to store anything here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With