{"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
The Java hashmap is a data structure that allows efficient access and storage of elements in them. The elements are stored in a Let us understand a few keywords first to better understand the HashMap.<\/p>\n\n\n\n Now that we are done with these terms, let us dive into how inserting elements into a hashmap works. Hashmap entries are done inside a table which is nothing but an array of By now you might have some questions in your mind! What if two keys have the same <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
A key is an element in a hashmap that helps us uniquely identify entries in it. In the example above, {1, 2, 3, 4, 5}<\/code> are the keys.<\/li>
As Wikipedia<\/a> describes it, a hash function<\/strong> is a function that can be used to map keys of arbitrary size to fixed-size values. The values returned by a hash function are called hash values<\/em>, hash codes<\/em>, digests<\/em>, or simply hashes<\/em>.<\/li>
Values are the elements that correspond to a key. In the example above, {1001, 1002, 1003, 1005, 100, 101}<\/code> are the values.<\/li><\/ul>\n\n\n\n
Nodes<\/code>. A
Node<\/code> is made up of
Hash<\/code>,
Key<\/code>,
Value<\/code> and some other components. When an element has to be inserted into the Hashmap, the key\u2019s
hash<\/code> is calculated which gives us the index of the table where the element has to be inserted.<\/p>\n\n\n\n
hash<\/code> or in other words what if there is a collision in the map? What is the size of the table?<\/p>\n\n\n\n