1

I am currently trying to learn how to properly override the equals() and HashCode() methods. I know that it is good practice to override HashCode() if I wish to override equals(), so that is what I am currently working on. The class I am currently using is my own class called Product with an int object variable called id, and two objects of this class are equal if their id is the same. This is how my equals looks like currently:

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Product that = (Product) o;

        return id == that.id;
    }

Now that I have an equals method that only compares a single variable from the class, how should I go about overriding the HashCode() method? IntelliJ suggests this, which does seem a bit too simplistic:

@Override
public int hashCode() {
    return id;
}

It also gives me the option to use the Java 7+ feature, which would give me this:

@Override
public int hashCode() {
    return Objects.hash(id);
}

Are any of these two methods a viable way to override HashCode? And if both are, which is better to use in what case?

3
  • Either is fine. I'd prefer the simplistic one, myself. Commented Dec 9, 2021 at 21:14
  • 1
    You are overthinking this. Returning the id is fine. Commented Dec 9, 2021 at 21:15
  • I wrote this a long time ago as a general solution for overridding hashCode: sourceforge.net/p/tus/code/HEAD/tree/tjacobs/util/… Commented Dec 9, 2021 at 21:17

1 Answer 1

1

If id is of type int (instead of Integer), id can't be null so you can use:

@Override
public int hashCode() {
    return id;
}

However, if you want to avoid the case that new Product(n) and Integer.valueOf(n) share the same hashCode, you can do:

@Override
public int hashCode() {
    int hash = getClass().hashCode();
    hash = 31 * hash + id;
    return hash;
}
Sign up to request clarification or add additional context in comments.

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.