July 25, 2021

Adding User Defined Object as key in HashMap

Adding the user defined object as key in HashMap is common in real time applications. As you are aware that key in HashMap should be unique. Or else duplicated key will override the previous value. Here I have created 2 java files: Employee.java, UserDefinedObjectinHashMap.java in a single package.

package com.chetasmind.mapPackage;

public class Employee {
    
    private int empID;
    private String empName;
    private double empSalary;
     
    public Employee() {
         
    }
    public Employee(int empID,String empName,double empSalary) {
        this.empID = empID;
        this.empName = empName;
        this.empSalary = empSalary;
    }
     
    public int getEmpID() {
        return empID;
    }
    public void setEmpID(int empID) {
        this.empID = empID;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public double getEmpSalary() {
        return empSalary;
    }
    public void setEmpSalary(double empSalary) {
        this.empSalary = empSalary;
    }
     
    @Override
    public String toString() {
         
        String empDetails = "Employee ID: "+this.empID+" Employee Name: "+this.empName+" Salary="+this.empSalary; 
        return empDetails;
         
    }
     
    @Override
    public int hashCode() {
         
        return (empID+empName.hashCode());
             
    }
     
    public boolean equals(Object obj) {
         
        if(obj instanceof Employee) {
            Employee emp = (Employee)obj;
            if(this.empID==emp.empID && this.empName.equals(emp.empName) && (this.empSalary==emp.empSalary))
                return true;
        }
        return false;
    }
}

As highlighted hashCode, equals method plays a major role. You have to write these methods. Later will modify these methods to cover various scenario.

package com.chetasmind.mapPackage;
import java.util.HashMap;

public class UserDefinedObjectinHashMap {

       public static void main(String[] args) {
	         
	        Employee emp1 = new Employee(101, "Ramesh", 85000);
	        Employee emp2 = new Employee(102, "Sagar", 65000);
	        Employee emp3 = new Employee(103, "Swati", 82000);
	        Employee emp4 = new Employee(101, "Ramesh", 85000);
	         
	        HashMap<Employee,String>obj = new HashMap<>();
	        obj.put(emp1, "value1");
	        obj.put(emp2, "value2");
	        obj.put(emp3, "value3");
	        obj.put(emp4, "value4");
	     
	        System.out.println(obj.size()); 
	    }
	}

For simplicity purpose i have used String as value in HashMap. but in real time application, this value will be user defined object or any other object. Now if you run above application, you will get the output as 3. Since while using the put method, JRE internally calls the hashCode method. While saving the emp4 object, hashCode of this object is same as emp1. So, call goes to equals method. Since these object has the same employee ID, Name, Salary, this method returns true. So, hashmap overrides the previous value: value1

Scenario 1: In above case what will happen if Employee.java does not have the method: hashCode ?? Try delete the hashCode method (Or you can comment out the method). Run the application. Output will be 4. Reason is : hashCode of each object is different. Since each object has different memory reference.(i mean each object refer to different memory location)

Scenario 2: Change the content of main method with below code. what is the output? Node: Comment the hashCode method

Employee emp1 = new Employee(101, "Ramesh", 85000);
Employee emp2 = new Employee(102, "Sagar", 65000);
Employee emp3 = new Employee(103, "Swati", 82000);
		
HashMap<Employee,String>obj = new HashMap<>();
obj.put(emp1, "value1");
obj.put(emp2, "value2");
obj.put(emp3, "value3");
obj.put(emp1, "value4");
		
System.out.println(obj.size());

If you run the above code, output will be 3. Since obj.put(emp1,”value4″) will give the same hashcode that of obj.put(emp1,”value1″)

Scenario 3: Change the hashCode method as mentioned below. change the content of main method as mentioned.

@Override
public int hashCode() {
       return 1;
} 
Employee emp1 = new Employee(101, "Ramesh", 85000);
Employee emp2 = new Employee(102, "Sagar", 65000);
Employee emp3 = new Employee(103, "Swati", 82000);
Employee emp4 = new Employee(101, "Ramesh", 85000);
		
HashMap<Employee,String>obj = new HashMap<>();
obj.put(emp1, "value1");
obj.put(emp2, "value2");
obj.put(emp3, "value3");
obj.put(emp4, "value4");
		
System.out.println(obj.size());

If you run the above application, output will be 3. Since content of hashmap is saved in single bucket. But equals method compares whether the hashmap key is same or not. emp4 key will replace the previous value.

The above application is also present in my github repository.
If you are writing java applications for the first time, refer my Project structure article.

Leave a Reply

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