anoop
anoop

Reputation: 13

two keys are same hashMap over write" the existing one?

How exactly hash map store data internally ... I knew it will calculate HashCode value of key and store it.If two key having same hash code it will put into same bucket. But why if "two keys are same hashMap over write" the existing one?

Upvotes: 1

Views: 3342

Answers (5)

UVM
UVM

Reputation: 9914

Hash functions are generallyy used for eliminating duplicate data.That is why collections type like Hashmap not allowing to store duplicate data. This algorithms has been used in database as well to eliminate possible duplicates while retrieval.

Upvotes: 1

Pakka Techie
Pakka Techie

Reputation: 684

Hashcode code main purpose is to reduce the number of invocation of equals method in the hash based collection. Same hash code need not return true for equals method. But if you say its equals is true, then it hascode should be true.

Upvotes: 1

fastcodejava
fastcodejava

Reputation: 41097

It will not overwrite the value if the hashCode() is same. It will overwrite only if they are equal by the equals method.

Upvotes: 4

See http://en.wikipedia.org/wiki/Hash_table and http://www.docjar.com/html/api/java/util/HashMap.java.html

A hash table or hash map is an array of linked lists, keyed by hashcode.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500425

Well, that's what it's designed to do. It's a mapping of key/value pairs, where any key is associated with 0 or 1 value. If you put a second value for a key, the entry for that key will be replaced.

It's not based just on the hash code though - it will test the keys for equality, too. Two keys can be unequal but have the same hash code. The important thing is that two equal keys must have the same hash code.

If you want to store multiple values for a single key, you should use something like Guava's Multimap.

Upvotes: 9

Related Questions