I am very much aware that there is a contract between equals() and hashCode() is basically: if equals() method is true, hashCode() mustreturn the same value, but vice versa not true.
Case-1: Only Hashcode is implemented, no equals method
public class Employee {
private String firstName;
private String lastName;
private int age;
public Employee() {
}
public Employee(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// No equals method implemented
@Override
public int hashCode() {
return 31;
}
public static void main(String[] args) {
Employee employee1 = new Employee("John", "Doe", 11);
Employee employee2 = new Employee("Jane", "Doe", 12);
Employee employee3 = new Employee("Joe", "Doe", 13);
Employee employee4 = new Employee("Joe", "Doe", 13);
Map<Employee, String> stringMap = new HashMap<>();
stringMap.put(employee1, "John");
stringMap.put(employee2, "Jane");
stringMap.put(employee3, "Joe");
stringMap.put(employee4, "Joe");
System.out.println(stringMap.size());
System.out.println(stringMap.get(employee4));
}
}
Output -
4
Joe
Case-2: Equals method implemented, but no hashcode
public class Employee {
private String firstName;
private String lastName;
private int age;
public Employee() {
}
public Employee(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return age == employee.age && Objects.equals(firstName, employee.firstName) && Objects.equals(lastName, employee.lastName);
}
public static void main(String[] args) {
Employee employee1 = new Employee("John", "Doe", 11);
Employee employee2 = new Employee("Jane", "Doe", 12);
Employee employee3 = new Employee("Joe", "Doe", 13);
Employee employee4 = new Employee("Joe", "Doe", 13);
Map<Employee, String> stringMap = new HashMap<>();
stringMap.put(employee1, "John");
stringMap.put(employee2, "Jane");
stringMap.put(employee3, "Joe");
stringMap.put(employee4, "Joe");
System.out.println(stringMap.size());
System.out.println(stringMap.get(employee4));
}
}
Output -
4
Joe
Why in both cases, its showing the same output? How the things are working internally?
If we properly implement the equals and hashcode method, then then we get the uniqueness among the collection (in this case, output - 3 Joe) and its advisable to use equals and hashcode together when operating on collection.