Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of Hashcode for custom class in Java [duplicate]

Tags:

java

hashcode

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?

like image 266
Dude Avatar asked Feb 01 '13 14:02

Dude


2 Answers

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;
like image 61
MTilsted Avatar answered Nov 05 '22 19:11

MTilsted


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.

like image 43
mellamokb Avatar answered Nov 05 '22 20:11

mellamokb