user7027544 user7027544 - 10 months ago 38
Java Question

Overriden equals method doesn't work

I have a problem with my equals method.
It works properly when I am colling it directly, but when I am using it with collections, I get different behaviour.
Here is the code:

class Employee {
int ID;
Employee(int ID) {
this.ID = ID;
public boolean equals(Employee e) {
return this.ID == e.ID;
public static void main(String[] args) {
Employee e1 = new Employee(0);
Employee e2 = new Employee(0);
Set<Employee> set = new HashSet<>();

Output is:


Answer Source

The reason of that behaviour is that your method equals(Employee e) doesn't override the equals from Object class.
You defined your own equals method, and both equals methods exists in your Employee class.
It's becouse equals from Object has Object as parameter, not Employee.
In line System.out.println(e1.equals(e2)); you are invoking your own equals method from Employee class but in line: set.add(e1); there is invoked method from Object class (equality based on address in memory). Your method could look like that:

public boolean equals(Object e) {
    if(!(e instanceof Employee))return false;
    return this.ID == ((Employee) e).ID;

Using @Override annotation is very useful in that case, becouse it gives compile time error if your method doesn't override equals(Object o) from super class.