How to override equals() and hashCode() method in java?
@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 |
Differentiate between == and equals().
Explain about transient variables in java?
Can you override static method in java?
What does nullpointerexception mean?
Name some OOPS Concepts in Java?
What is void class in java?
What is treeset in java?
How is hashcode calculated in java?
what is finalmethod & final variable with example?
Write java program to reverse string without using api?
How to make a method thread safe without using synchronized keyword?
8 Answers Persistent, Societe Generale,
what do you mean by classloader in java?