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 |
What is design pattern and there types?
What is the internal implementation of set in java?
What is static keyword?
Which java version is latest?
What are keywords and reserved words in java?
What is the use of collections in java? How it is implemented in real time applications?
Why java uses the concept of the string literal?
Compare overloading and overriding?
What is serialversionuid?
How many return statement are allowed in a function?
What are the operands of instanceof operator?
Is array dynamic in java?