How to override equals() and hashCode() method in java?



How to override equals() and hashCode() method in java?..

Answer / 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

More Core Java Interview Questions

What is vector capacity in java?

0 Answers  


What is the difference between logical data independence and physical data independence?

0 Answers  


Explain the importance of finally over return statement?

0 Answers  


What is meant by local variable and instance variable?

0 Answers  


How multipleInheritance is possible in java?

18 Answers   Satyam,






What are different exception types exceptions available in java ?

0 Answers  


What is the difference between variable & constant?

0 Answers  


What is a byte array?

0 Answers  


Explain the difference between protected and default access.

0 Answers  


What is the set interface in java programming?

0 Answers  


How do you reverse sort a list in java?

0 Answers  


Can an anonymous class be declared as implementing an interface and extending a class in java programming?

0 Answers  


Categories