How HashMap Works in Java ?

Answer : HashMap is one of the most widly used implementation of Map to store key-value pairs…

How HashMap Works in Java ?

  • HashMap is one of the most widly used implementation of Map to store key-value pairs. To implement HashMap with ArrayList.
  • It is provides two basic HashMap functions they are: get(key) and put(key, value).
  • While storing code to be checking the duplicate values. While duplicate values are presents to be removed.
  • Implementation should not be used as a replacement of HashMap. Also while testing the code, make sure that the Object used in the KEY has proper implementation of equals() method.

Example:

[pastacode lang=”java” manual=”package%20com.journaldev.util%3B%0A%0Aimport%20java.util.ArrayList%3B%0Aimport%20java.util.List%3B%0A%0Apublic%20class%20MyHashMap%20%7B%0A%0A%09class%20Container%7B%0A%09%09Object%20key%3B%0A%09%09Object%20value%3B%0A%09%09public%20void%20insert(Object%20k%2C%20Object%20v)%7B%0A%09%09%09this.key%3Dk%3B%0A%09%09%09this.value%3Dv%3B%0A%09%09%7D%0A%09%7D%0A%09%0A%09private%20Container%20c%3B%0A%09private%20List%3CContainer%3E%20recordList%3B%0A%09%0A%09public%20MyHashMap()%7B%0A%09%09%0A%09%09this.recordList%3Dnew%20ArrayList%3CContainer%3E()%3B%0A%09%7D%0A%09%0A%09public%20void%20put(Object%20k%2C%20Object%20v)%7B%0A%09%09this.c%3Dnew%20Container()%3B%0A%09%09c.insert(k%2C%20v)%3B%0A%09%09%2F%2Fcheck%20for%20the%20same%20key%20before%20adding%0A%09%09for(int%20i%3D0%3B%20i%3CrecordList.size()%3B%20i%2B%2B)%7B%0A%09%09%09Container%20c1%3DrecordList.get(i)%3B%0A%09%09%09if(c1.key.equals(k))%7B%0A%09%09%09%09%2F%2Fremove%20the%20existing%20object%0A%09%09%09%09recordList.remove(i)%3B%0A%09%09%09%09break%3B%0A%09%09%09%7D%0A%09%09%7D%0A%09%09recordList.add(c)%3B%0A%09%7D%0A%09%0A%09public%20Object%20get(Object%20k)%7B%0A%09%09for(int%20i%3D0%3B%20i%3Cthis.recordList.size()%3B%20i%2B%2B)%7B%0A%09%09%09Container%20con%20%3D%20recordList.get(i)%3B%0A%09%09%09%2F%2FSystem.out.println(%22k.toString()%3A%22%2Bk.toString()%2B%22con.key.toString()%22%2Bcon.key.toString())%3B%0A%09%09%09if%20(k.toString()%3D%3Dcon.key.toString())%20%7B%0A%09%09%09%09%0A%09%09%09%09return%20con.value%3B%0A%09%09%09%7D%0A%09%09%09%0A%09%09%7D%0A%09%09return%20null%3B%0A%09%7D%0A%09%0A%09public%20static%20void%20main(String%5B%5D%20args)%20%7B%0A%09%09MyHashMap%20hm%20%3D%20new%20MyHashMap()%3B%0A%09%09hm.put(%221%22%2C%20%221%22)%3B%0A%09%09hm.put(%222%22%2C%20%222%22)%3B%0A%09%09hm.put(%223%22%2C%20%223%22)%3B%0A%09%09System.out.println(hm.get(%223%22))%3B%0A%09%09hm.put(%223%22%2C%20%224%22)%3B%0A%09%09%0A%09%09System.out.println(hm.get(%221%22))%3B%0A%09%09System.out.println(hm.get(%223%22))%3B%0A%09%09System.out.println(hm.get(%228%22))%3B%0A%09%7D%0A%0A%7D” message=”” highlight=”” provider=”manual”/]

Output:

3
1
4
null
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like