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 lambda in java?

0 Answers  


Does isempty check for null?

0 Answers  


what is the difference between String s="hello"; and String s=new String("hello");?

3 Answers  


Can we have a try block without catch block?

0 Answers  


what is meta-Inf?

2 Answers   Polaris,






What is java class writing rules?

1 Answers   Oracle,


What is a class instance variable?

0 Answers   Tech Mahindra,


What are the wrapped, classes?

0 Answers  


How would you dynamically allocate memory to an array?

0 Answers   Atos Origin,


What is the use join() in Threads ?

5 Answers   HCL,


How do I know if java is installed?

0 Answers  


What is an error in java?

0 Answers  


Categories