As the name suggests, HashMap is a concrete implementation of Map, which follows a technique called 'Hashing'.
As we know Map stores the values in the form of Key and Value pairs. Same applies for HashMap as well.
In a HashMap, it's only the key that is calculated based on Hashing technique.
Have a look at Hash Code and Hash Collision.
Since, the insertion is based on Hash Code, a HashMap is unsorted and unordered.
HashMap(): Creates a HashMap with initial capacity 16. HashMap(int initialCapacity) : Creates a HashMap with a custom initial capacity. HashMap(int initialCapacity, float LoadFactor) : Creates a HashMap with a custom initial capacity and custom Load Factor. HashMap(Map map) :
A HashMap can be defined by :
or :
We have defined the HashMap and specified the key - value pair type using the angular brackets(i.e. < >). And as we can see the key has to be of type Integer and value needs to be of type String.
The angular brackets(i.e. < >) ensures type safety and are known as Generics(We will be looking later). By imposing Generics we make sure that the key and the value must be of Integer and String type.
1. We have created a HashMap() using the below format.
2. Then, we have added 'John' to the HashMap, with '1' as the Key.
Key | Value |
---|---|
1 | John |
3. Next, we have added 'Paul' to the HashMap, with '2' as the Key.
Key | Value |
---|---|
1 | John |
2 | Paul |
4. After that, we have added 'Tom' to the HashMap with '1' as key again.
And guess what happened? 'John' gets replaced with 'Tom'.
Key | Value |
---|---|
1 | Tom |
2 | Paul |
5. Now, if we want to get the value for the 'key' 1, we have used the get() method.
The value is 'Tom' for key '1'.
6. Next, we tried to remove an Entry from the HashMap. And we have done using the remove() method.
Key | Value |
---|---|
2 | Paul |
7. Then we tried to check if the key '2' is present in the HashMap or not.
Let us add a few values to a HashMap and see how do we fetch them.
In the above code, after we have added three Entries(i.e. Key and Value Pair) to the HashMap. We have used the for each loop to iterate the Entries of the Map.
A Key - Value pair in a map is called as an Entry. So, in the 'Map' interface there is an 'Entry' interface.
And 'Map.Entry' type object actually holds a key - value pair or an Entry.
So, to fill this 'Map.Entry entry', we need a Set of HashMaps in the form of Key - Value pairs.
Now, 'myHashMap.entrySet()' solves this purpose. 'entrySet()' method returns a Set of key and values from the HashMap.
Now, 'myHashMap.entrySet()' solves this purpose. 'entrySet()' method returns a Set of key and values from the HashMap.
So, when we get the key - value pair in the 'entry' object of 'Map.Entry'. We can get the key using 'entry.getKey()' and value using 'entry.getValue()'.
If we look at the output, the order is not maintained. Because the insertion is based on HashCode of the key.