Possible Duplicate:
Overriding equals and hashCode in Java
I am supposed to implement hashcode and equals for Custom class Person. Person consists of
firstname
lastname
I am supposed to implement equals and hashcode such that two people with firstname and lastname should return true for equals and should be accepted by Hashmap. I have implemented Person class like this:
public class Person {
String firstname;
String lastname;
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return firstname.hashCode()+lastname.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Person u=(Person) obj;
return u.firstname.equals(firstname) && u.lastname.equals(lastname);
}
}
Is the implementation of Hashcode correct here? Even though I am getting the expected result,I want to know if this implementation is correct?
There is a slight problem with your equals method because it will throw an exception if obj is null or not a Person
, so you should add the following to the top of your equals:
if(obj==null || !(obj instanceof Person))
return false;
There is an excellent discussion of proper equals
and hashCode
implementation here:
Whenever a.equals(b), then a.hashCode() must be same as b.hashCode()
This is the only rule that matters. There is no correct implementation of a hashCode
besides this one rule. There are better and worse hash codes in terms of performance and hash collisions, but that's another topic altogether.
Your code appears to be correct according to that rule, because if a.equals(b)
, then firstname.hashCode()+lastname.hashCode()
should be the same value for both a
and b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With