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

Can one thread block the other thread?

608


Can we return null in java?

643


What are the concepts of 'OOPS'?

602


What are the 8 data types in java?

523


Explain the difference between abstraction and encapsulation.

537






What is a line break example?

580


What if I write static public void instead of public static void in java?

580


Explain differences between checked and unchecked exceptions in java?

641


Define locale.

588


How do you use substring in java?

549


Why do we need hashmap in java?

559


What are the methods used to implement for the key object in the hash map?

568


Can you give names of Container classes?

1858


Which class is used by server applications to obtain a port and listen for client requests?

493


Can we overload run() method in java?

599