Best Practice: What can be the hashCode() method implementation if custom field used in equals() method are null?

Posted by goodspeed on Programmers See other posts from Programmers or by goodspeed
Published on 2014-06-04T16:30:23Z Indexed on 2014/06/04 21:41 UTC
Read the original article Hit count: 209

Filed under:

What is the best practice to return a value for hashCode() method if custom field used in equals are null ?

I have a situation, where equals() override is implemented using custom fields. Usually it it is better to override hashCode() also using that custom fields used in equals(). But if all the custom fields used in equals() are null, then what would be the best implementation for hashCode()?

Example:

class Person {
    private String firstName;
    private String lastName;        
    public String getFirstName() {
        return firstName;
    }        
    public String getLastName() {
        return lastName;
    }
    @Override
    public boolean equals(Object object) {
        boolean result = false;
        if (object == null || object.getClass() != getClass()) {
            result = false;
        } else {
            Person person = (Person) object;
            if (this.firstName == person.getFirstName()
                && this.lastName == tiger.getLastName()) {
                result = true;
            }
        }
        return result;
    }        
    @Override
    public int hashCode() {
        int hash = 3;
        if(this.firstName == null || this.lastName == null) {
            // <b>What is the best practice here, </b>
            // <b>is return super.hashCode() better ?</b>
        }        
        hash = 7 * hash + this.firstName.hashCode();
        hash = 7 * hash + this.lastName.hashCode();
        return hash;
    }
}
  1. is it required to check for null in hashCode() ?
  2. If yes, what should be returned if custom values are null ?

© Programmers or respective owner

Related posts about java