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
What will happen if non-synchronized method calls a static synchronized method and what kind of lock it acquires?
What is the different types of functions?
What are the drawbacks of singleton class?
What does replaceall do in java?
Can memory leak in java?
Can we use switch statement with strings?
What is the return type of the main method?
What is the main advantage of passing argument by reference?
whatis Home interface and Remoteinterface? with example?
Is empty set an element of empty set?
How to declare objects of a class ?
What is the difference between throw and throws keywords?
Why java is considered as platform independent?
How many java versions are there?
What is the meaning of course?