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 is a container in a gui?
What is the use of accept () method in java?
What is blank final variable?
What are thread groups?
Explain java code for recursive solution's base case?
Why Set interface contains unique elements, what internally implemented for this so that it contains unique elements?
What are three ways in which a thread can enter the waiting state in java programming?
Why do you canvas?
Why stringbuilder is not thread safe?
What is numeric data type?
What is the purpose of the finalize() method?
What are the advantages of encapsulation in java?
What is the relationship difference the canvas class and the graphics class?
Can this keyword be used to refer static members?
Why is multithreading important?