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

Can an exception be rethrown?

4 Answers   Wipro,


What do you mean by object?

0 Answers  


what is servlet enginee?

0 Answers   Covansys,


what is the meaning of java.lang and java.util

6 Answers  


what are the oops concept in java explain with real time examples

24 Answers   Accenture, Bosch, Consummate Technologies, CTS, Current Technologies, iNautix, Infosys, Kekran Mekran, QA InfoTech, RTRT, SofTech, Tech Mahindra, Thorogood, Timios, Wipro,






what is polymorphism?

5 Answers   Zensar,


If a method is declared as protected, where may the method be accessed?

0 Answers  


What's the purpose of static methods and static variables?

0 Answers  


List the different types of classloaders in java.

0 Answers  


Why is multithreading important?

0 Answers  


how jvm allocates memory for stack?

1 Answers   HP, Ramco,


What is the difference between a method and a function in alice?

0 Answers  


Categories