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 the final class?
State some situations where exceptions may arise in java?
Can we override constructor in java?
What is the integer of 16?
what is synchronization and why is it important? : Java thread
What is type parameter in java?
Explain the difference between jvm and jre?
What is string buffer?
Give differences between Quicksort &Mergesort. When should these sorts be used andwhat is their running time in java?
Is passing by reference faster?
What is default locale java?
If an application has multiple classes in it, is it okay to have a main method in more than one class?
Does sprintf add a null terminator?
What are different ways of object creation in java ?
Can java program run without jre?