0

I have created an Employee class having name and employeeNo . I am overriding equals and hashcode method.

@Override
public boolean equals(Object obj) {
       final Employee other = (Employee) obj;

 if (this.employeeNo == other.employeeNo && this.name.equals(other.name)) {
                return true;
            }

            return false;
    }

@Override
public int hashCode() {
    int hash = 3;
    hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
    hash = 53 * hash + this.employeeNo;
    return hash;
}

My test class

Employee p = new Employee();
        p.setName("v");
        p.setEmployeeNo(1);

        Employee p1 = new Employee();
        p.setName("v");
        p.setEmployeeNo(1);

        System.out.println(p==p1); // Print false . why?
Thinker
  • 6,820
  • 9
  • 27
  • 54

2 Answers2

10
System.out.println(p==p1);

does not implicitly call equals(. It compares the references which are different here. Use:

System.out.println(p.equals(p1));

instead.

Also:

Employee p1 = new Employee();
p.setName("v");
p.setEmployeeNo(1);

uses p, where p1 should be used.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

The error maybe in this line:

if (this.employeeNo == other.employeeNo && this.name.equals(other.name)) {
    return true;
}

This condition will only become true, if booth employeeNr are the same. If employeeNr is of type Integer and not int.

If is false becuase equals() is not calles.

a==b will check iif the objects are the same

e.equals(b) will call the equals()

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79