Thursday, 26 March 2015

How hash map works if it has same key of strings

it was great discussion with my friend over working of hash-map with the same key.

The question was.
Does hash map store the same key? if yes then

What happens when a duplicate key is put into a HashMap?

Here is example of store ing duplicate key guess the output?

import java.util.*;
public class MyHashMap {
 public static void main(String args[]){
 
  HashMap<String,String> hm=new HashMap<String,String>();

  hm.put("Vipul","1000");
  hm.put("Vipul","2000");
  hm.put("Vipul","3000");

 
  System.out.println(hm.get("Vipul"));
  for(Map.Entry m:hm.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

ANS Is

Vipul 3000

--------------------------------------------------------------------------------------------
now it is getting more complex....?

What will be size of hash-map in this case?
Ans: ONE
--------------------------------------------------------------------------------------------
import java.util.*;
public class MyTestHashMap {
 public static void main(String args[]){
 
  HashMap<String,String> hm=new HashMap<String,String>();

  hm.put("Vipul","1000");
  hm.put("Vipul","2000");
  hm.put("Vipul","3000");

 
  System.out.println(hm.get("Vipul"));
  for(Map.Entry m:hm.entrySet()){
   System.out.println(hm.size+" "+m.getKey()+" "+m.getValue());
  }
 }
}

There are some more code as well I will add soon
In case your finding is different please comment.