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?