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
When we should use serialization?
How is Object Oriented Programming different from Procedure Oriented Programming?
What is thread pool? How can we create thread pool in java?
What are methods in java?
Can we have a method name same as class name in java?
What is t in parametric equations?
How do we access static members in java?
How do you compare arrays in java?
What is keyset in java?
Can we override constructor in java?
How many arguments can a method have java?
What is a dot notation?
How many bits is a word?
What is an accessor?
What is the difference between multiple processes and multiple threads?