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?
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.