Friday, 13 April 2012

Does the Hashmap allow duplicate key or how Hashmap finds duplicate key ???

Hi Friends

Today i am going to discuss a very interesting topic about HashMap. Java HashMap doesn't allow the the duplicate key but it allows the duplicate value. what does it mean that it doesn't allow duplicate. How it internally checks the key is duplicate, any guess? Here people think that internally HashMap would have checked in the existing key that it already there or not.
Can you think if the size of it big and we want to enter another key which is already exist then process of comparing with each existing key will be too vast and it will take lots of time, but when we tries it not takes much time. Here i am going to make you little bit shocked.
Actually whatever we discussed about duplicate keys, HashMap never does the above process to check the duplicate key. Whenever we use the

the it calls the hashCode function for key. hashCode functions returns the memory a memory location associated with the key and copy the value to this particular location. if use again key with different value then the put replace the old value with new value. For us it looks that its not allowing duplicate key but actually it always point to same memory location for a single key. if we use same key again for adding into the HashMap it overrides the old value with new value.


import java.util.HashMap;

public class CheckDuplicate
public static void main(String[] args) {
HashMap map=new HashMap();
map.put("key", "first");
map.put("key", "second");

Out Put :: second

We can understand from example, if it prevent duplicate then the output should have "first". but its overriding the old value so the out put is "second".