1

In the code below I want to use the "term" attribute to generate the hash code. How to use this String attribute to generate hash code?

class Term {
    String term;
    @Override
    public boolean equals(Object o) {
        if (o instanceof Term) {
            return this.term.equals(((Term)o).term);
        }
        return false;
    }
    @Override
    public int hashCode() {
    }
}

3 Answers 3

7

Just use String#hashCode() method with a null check. That would be enough:

@Override
public int hashCode() {
    int prime = 31;
    return prime + (term == null ? 0 : term.hashCode());    
}

You should also modify the equals() method to do the null check on this.term before hand.

Sign up to request clarification or add additional context in comments.

3 Comments

@user949300 Good catch. Fixed it.
There is no need to modify the equals() method because instanceof will return false if the argument is null.
@SlavaSt I'm talking about the case when this.term is null.
2

You can use Objects if you use JDK 1.7 or more.

@Override
public int hashCode() { 
   int prime = 31;
   return prime + Objects.hashCode(this.stringAtrribute);    
}

For multiple attributes:

@Override
public int hashCode() { 
   int prime = 31;
   return prime + Objects.hash(this.attributOne,this.atrributeTwo);    
}

And yes ofcourse as with the previous answers the equal and hashcode method should have consistency.

Comments

1

Eclipse can write this code for you. Just choose Generate hashCode and equals from the Source menu.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.