0

in my Event class, it has a name variable as a String, and I want the name to be the unique identifier of an object. In implementing the hashCode() method, which way is recommended or right?

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}

or

@Override
public int hashCode() {
    return name != null ? name.hashCode() : 0;
} 
1
  • first hashcode == second hashcode + 31. What's the point? Commented Sep 15, 2014 at 1:57

2 Answers 2

3

You may as well just use the default Java hashCode since it works well enough for most purposes. Don't overcomplicate: the second, simpler function will work just fine.

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

Comments

1

The first one is a template when there are many attributes (possibly of various types), but if you only have a String the default hashCode() defined on String (inherited from Object) will do fine.

2 Comments

I have more fields, like boolean, and Long, but the String "name" is going to be the natural and unique identifier.
Yes that's what I meant, then the second one is indeed the most appropriate.

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.