user325643
user325643

Reputation: 363

Is "key" stored twice in 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?

Upvotes: 3

Views: 863

Answers (4)

Daniel
Daniel

Reputation: 6775

I don't know for sure, but it does not seem like this would be necessary. When accessing a bucket in a HashMap, the hash function is applied to the key that is being searched. It could then compare this key to the key that is stored.

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308269

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.

Upvotes: 2

Jesper
Jesper

Reputation: 207016

No. If you want to know exactly how HashMap works, then you can lookup the source code. There should be a file named src.zip in your JDK installation directory that contains the Java source code of all the classes and interfaces in the standard library.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

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

Upvotes: 1

Related Questions