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 main function purpose?
What is the default size of load factor in hashing based collection?
Explain illegalmonitorstateexception and when it will be thrown?
Can an arraylist be empty?
How to sort a collection of custom Objects in Java?
What are the parts of a method?
Name the packages in JDK?
Why do we need singleton?
Why we override equals() method?
What is the difference(or similarity if there are some) between object and a variable?
Is java pass by value or pass by reference?
Which java ide is used the most?