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
Can one thread block the other thread?
Can we return null in java?
What are the concepts of 'OOPS'?
What are the 8 data types in java?
Explain the difference between abstraction and encapsulation.
What is a line break example?
What if I write static public void instead of public static void in java?
Explain differences between checked and unchecked exceptions in java?
Define locale.
How do you use substring in java?
Why do we need hashmap in java?
What are the methods used to implement for the key object in the hash map?
Can you give names of Container classes?
Which class is used by server applications to obtain a port and listen for client requests?
Can we overload run() method in java?