Hashmap in Java: 5 Detailed Facts

Introduction to Hashmap in Java

Hashmap is one of the data structures provided by java. It contains a set of unique keys and corresponding values. Once successfully stored in a hashmap, they are stored as key-value pairs and they can be retrieved at any point in time with the key.

If no element is present in the Hashmap, it will throw a NoSuchElementException.
Hashmap stores objects as object reference hence we can not store any primitive datatypes instead we need to store the Wrapper classes for the primitive data types.

Hashmap uses Hashing technique internally hence the searching becomes faster.HashMap extends abstract class AbstractMap which implementation the Map interface.it also implements a Cloneable and Serializable interface.

HashMap doesn’t allow duplicate keys but allows duplicate values.HashMap allows one null key and null values to be inserted. The order of the Hashmap is not as we insert the keys.
Hapmap is not synchronized so it is possible for two threads to modify it at once,leading to possible errors.

General form of Hashmap is :

HashMap<Object, Object> myMap = new HashMap<>();

When we say HashMap can contain any numbers of objects inside it, so there comes two important things to remember:
1. The initial capacity
2. How HashMap grows: Rehashing
3. When the HashMap grow: The load factor

See also  How to stop a Test Process If that Is Hanged or Went To Infinite loop

The initial capacity of the HashMap is not fixed for every case. But it is assigned a higher number so that HashMap does not have to increase its size. The commonly given initial size is 16.

In case JVM sees that the objects are getting added in a huge manner, it will try to increase the capacity of the HashMap by using the rehashing technique. In this process, the capacity becomes double the initial capacity.

The load factor determines when to call the rehashing technique to increase its size. This is required as the rehashing takes some time.

The load factor falls in the range of 0 to 1. The majorly used load factor is .75 that gives JVM and the coder with optimum performance for the HashMap.

Further visit: How To Set Classpath in Java – 7 Important Steps To Follow

HashMap class provides 4 constructs as follows:

NoConstructor NameConstructor DescriptionInitial CapacityLoad Factor
1HashMap()default constructor16.75
2HashMap(int initial capacity)creates a HashMap with the initial capacity provided in the argumentcapacity.75
3HashMap(int initial capacity, float load factor)creates a HashMap with the initial capacity and load factor providedcapacityloadFactor
4HashMap(Map mvmap)creates a HashMap from the specification from another Map-myMapas per Map-myMapas per Map-myMap

The HashMap class provides the following methods to work with:

NoMethod NameMethod DescriptionReturnComment
1get(Object Key)Returns the corresponding value for the keyObject
2put(Object Key,Object Value)Insert the value with association with the key in the HashMapObject
3keySet()Returns the set view of the HashMapSet
4values()Returns the values of the HashMap
5containsKey(Object key)Checks if the key is present in the HashMapboolean true or false
6remove(Object key)removes the key from the HashMapObjectRemoves the key and value from HashMap
7isEmpty()Checks if HashMap is emptyboolean true or false
8containsValue(Object value)Checks if HashMap has a mapping key for the value specifiedboolean true or false
9clone()clones a HashMapObject
10entrySet()Returns the set view of the HashMapSet
11size()Returns size of the HashMapint
12putAll(Map myMap)copy all elements from myMap to current HashMap
13clear(()clears/remove all mappings from the HashMapvoid
See also  Class Boolean in Java

An Example:

import java.util.HashMap;
public class HashMapTest{
 public static void main(String []args){
        //let us create a HashMap of Roll Number-Name 
        HashMap<integer><Sring> rollNumber=new HashMap<integer><Sring>;();
        //check the initial values- it should be blank
        System.out.println("Initial HashMap contains"+rollNumber);
        //Add member to the class
        //check the updated Hashmap
        System.out.println("updated HashMap contains"+rollNumber);
        // test if the HashMap is having a valid key
        boolean flag1=rollNumber.containsKey(1);
        System.out.println("The key 1 present in the HashMap "+flag1);
        //negative test
        boolean flag2=rollNumber.containsKey(6);
        System.out.println("The key 6 present in the HashMap "+flag2);
        //get values from HashMap
        String name=rollNumber.get(1);
        System.out.println("The value correspond to key 1 "+name);
        //remove a key from HashMap
       //check the contents of the HashMap
        System.out.println("updated HashMap contains"+rollNumber);
        //remove everything from the HashMap
         System.out.println("updated HashMap contains"+rollNumber);

The output of the code is :
$javac HashMapTest.java
$java -Xmx128M -Xms16M HashMapTest
Initial HashMap contains{}
updated HashMap contains{1=Avishek, 2=Bishal, 3=Parvez, 4=Mainul}
The key 1 present in the HashMap true
The key 6 present in the HashMap false
The value corresponding to key 1 Avishek
updated HashMap contains{1=Avishek, 3=Parvez, 4=Mainul}
updated HashMap contains{}

Share and Enjoy !

Leave a Reply

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