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

How to synchonise HashMap

4 Answers   IBM,


Are global variables initialized to zero?

0 Answers  


What is the relationship between clipping and repainting under awt?

0 Answers  


How to stop a thread in java? Explain about sleep () method in a thread?

0 Answers  


import java.io.*; class Demo { public static void main(String args[]) { File f=new File("1234.msg"); String arr[]=f.list(); System.out.println(arr.length); } }

3 Answers   IBM, Ramco,






Why are strings immutable in Java?

1 Answers  


what is the significance of listiterator in java?

0 Answers   IBS,


Explain about core java?

0 Answers  


Can you run the product development on all operating systems ?

1 Answers  


In what circumstances, compiler will supply a default constructor for a class?

4 Answers  


What is jvm? Why is java called the platform independent programming language?

0 Answers  


What is boolean strategy?

0 Answers  


Categories