Whenever you are working with the collections HashMap, HashSet then you have to override pojo hashcode and equals method.
package com.stackoverflow.java.core; import java.util.HashMap; import java.util.Map; public class Employee { private String name; private String sex; private int salary; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int hashCode() { //Not taken care when genrating hashcode. int hashcode = this.age * 2 + this.salary * 2; return hashcode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != this.getClass()) return false; Employee employee = (Employee) (obj); if ((this.name.equals(employee.name) && (this.sex.equals(employee.sex) && (this.age == employee.age) && (this.salary == employee.salary)))) { return true; } else { return false; } }
Reply