How to override equals() and hashCode() method in java?
Answer Posted / javamasque
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Employee emp = (Employee) obj;
return id == emp.id
&& (firstName == emp.firstName
|| (firstName != null && firstName.equals(emp.getFirstName())))
&& (lastName == emp.lastName || (lastName != null && lastName .equals(emp.getLastName())));
}// equals method ends
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 :frstName.hashCode());
result = prime * result + id;
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}// hashCode method ends
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers
How do you ensure that n threads can access n resources without deadlock?
what is interface in java? Explain
Which is better singleton or static class?
What causes memory leak in java?
Where will it be used?
What is the use of using enum to declare a constant?
What are the restriction imposed on a static method or a static block of code?
What is difference between pointer and reference?
What is thread life cycle?
What are the 8 data types in java?
What happens if an exception is not handled in a program?
What is the latest java version?
What is final, finally, finalize?
Can we access instance variables within static methods ?
What is the difference between the prefix and postfix forms of the ++ operator?