{"id":19,"date":"2020-08-09T05:34:30","date_gmt":"2020-08-09T05:34:30","guid":{"rendered":"https:\/\/system.camp\/index.php\/2020\/08\/09\/java-hashmap\/"},"modified":"2020-10-06T09:56:51","modified_gmt":"2020-10-06T09:56:51","slug":"java-hashmap","status":"publish","type":"post","link":"https:\/\/system.camp\/tutorial\/java-hashmap\/","title":{"rendered":"Java Hashmap"},"content":{"rendered":"\n

What is a Hashmap and why do we need it?<\/h3>\n\n\n\n

The Java hashmap is a data structure that allows efficient access and storage of elements in them. The elements are stored in a <key, value><\/code> format. It implements the Map<\/code> interface and it is important to note that the key<\/code> must be unique. This essentially means that if you insert <key = 5, value = 100><\/code> first and then insert <key = 5, value = 101><\/code> into the same hashmap, only the latter remains. This is illustrated in the code below. It allows us to access its elements in O(1)<\/code> and should be used when the order of accessing elements is not important.<\/p>\n\n\n\n

package com.company;\nimport java.util.HashMap;\nimport java.util.Map;\npublic class Main {\n    public static void main(String[] args) {\n        Map<Integer, Integer> hashMap = new HashMap<>();\n        hashMap.put(1, 1001);\n        hashMap.put(2, 1002);\n        hashMap.put(3, 1003);\n        hashMap.put(4, 1005);\n        hashMap.put(5, 100);\n\t\t  \/\/ This gives output as 100\n        System.out.println(hashMap.get(5));\n\t\t  hashMap.put(5, 101);\n\t\t  \/\/ This gives output as 101 because the previous entry is removed\n        System.out.println(hashMap.get(5));\n    }\n}\n<\/code><\/pre>\n\n\n\n

How are elements inserted into the HashMap?<\/h3>\n\n\n\n

Let us understand a few keywords first to better understand the HashMap.<\/p>\n\n\n\n