hashcode() and equals() method

hashcode() and equals() methods both are provided by the object class.Object class is the base class of java object.So all the object by default override this two method.

equals() method compare weather two object are equal

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id;
}

hascode() method based on hashing return a int hascode value to store on hash table.It will provide same hash value if the object are equal by using equals() method.

String a = "Andrew";
String b = "Andrew";

if(a.equals(b)){ //checking the equality of objects using equals() methods
System.out.println("a & b are equal variables, and their respective hashvalues are:" + " "+ a.hashCode() + " & " + b.hashCode());

}
output:
a & b are equal variables, and their respective hash values are: 1965574029 & 1965574029

Program based on collection set is below

public class Employee
{
int id;
String name;

public Employee(String name, int i)
{
this.id = i;
this.name = name;
}

public static void main(String[] args)
{
Employee emp1 = new Employee("Pandiyan",1);
Employee emp2 = new Employee("Pandiyan",1);

HashSet<Employee> sa=new HashSet<>();
sa.add(emp1);
sa.add(emp2);

System.out.println(sa);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id;
}

@Override
public int hashCode() {
return Objects.hash(id, name);
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}