-2

In the below code, the overridden method hashCode returns the result. Why are we assigning so many values to result variable before returning it? I got the below code from some tutorials:

public class User {
private String name;
private int age;
private String passport;

//getters and setters, constructor

@Override
public boolean equals(Object o) {

    if (o == this) return true;
    if (!(o instanceof User)) {
        return false;
    }

    User user = (User) o;

    return user.name.equals(name) &&
            user.age == age &&
            user.passport.equals(passport);
}

//Idea from effective Java : Item 9
@Override
public int hashCode() {
    int result = 17;
    result = 31 * result + name.hashCode();
    result = 31 * result + age;
    result = 31 * result + passport.hashCode();
    return result;
}

}

Kiran Cyrus Ken
  • 379
  • 1
  • 3
  • 17
  • If you're wondering why it's in a variable that gets modified instead of a single return statement, try writing it both ways and see which is easier to read, write and extend. – that other guy Sep 28 '18 at 19:41
  • You aren't *really* assigning many values. You are just using the variable as a temporary holder. You could write this as `return 31 * (31 * (31 * 17 + name.hashCode()) + age) + passport.hashCode()`; but it just isn't as clear like that, it's harder to modify etc. – Andy Turner Sep 28 '18 at 19:48
  • 2
    It's not very clear what you're confused by. The style? The logic? Be more specific. And the attitude is totally unnecessary and unhelpful. – shmosel Sep 28 '18 at 19:48

1 Answers1

1

The successive assignments to result are to "scramble" the information contained in it, and to add more information from other sources. Note that result is on both sides of the assignment. Starting with a base value of 17, we then do this a few times:

result = 31 * result + someValue;

By multiplying result by 31, we move the existing value to the left a few bits, then add more bits by adding another value to it.

This is a very fast way to come up with a fairly unique hash code for every User object that you can define.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • People claim that there is no more advantage to using this 17 + 31 * approach to `hashCode()` implementations, and using `Objects.hashCode()` is equivalent since JDK 1.7. Is that a statement that holds past the 21st year of the 21st century? – ikaerom Dec 10 '22 at 15:11