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


Please Help Members By Posting Answers For Below Questions

What is serialization in java?

778


What is the purpose of garbage collection in java? When is it used?

788


What is difference between hashset and hashmap?

780


What is variable and rules of variable?

743


What is locale?

795


What are aggregate functions explain with examples?

773


What is java algorithm?

698


How do you create immutable object in java?

769


What classes of exceptions may be caught by a catch clause in java programming?

919


What are the basic concepts of OOPS in java?

748


How to handle a web browser resize operation?

745


What is the difference between static and global variables and also define what are volatile variables?

798


What is the difference between preemptive scheduling and time slicing?

819


Why put method is idempotent?

650


How do you use compareto in java?

736