Explaining statements in hashCode() method in plain English

51 views Asked by At

I am trying to learn the basics of the hashCode() method in Java. I read an article by Eugen Baeldung this morning, but I'm still having trouble with something in the code he posted. I think only the code for the method itself is needed, but I'm posting the whole code just in case.

package com.baeldung.hashcode.standard;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class User {

    private final Logger logger = LoggerFactory.getLogger(User.class);
    private long id;
    private String name;
    private String email;

    public User(long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null)
            return false;
        if (this.getClass() != o.getClass())
            return false;
        User user = (User) o;
        return id == user.id && (name.equals(user.name) && email.equals(user.email));
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 31 * hash + (int) id;
        hash = 31 * hash + (name == null ? 0 : name.hashCode());
        hash = 31 * hash + (email == null ? 0 : email.hashCode());
        return hash;
    }
    // getters and setters here   
}

In the hashCode() method, the third and fourth lines confuse me. It looks like with name.hashCode() and email.hashCode() we are calling the hashCode() method on the name and the email, but we are in the middle of the hashCode() method itself when these are being called. Is this supposed to be recursive? I don't have a great grasp of recursive functions, but those are the only thing I'm aware of where you call a function inside the very function that's being called. If it's not recursive, can someone explain to me what it is? And can someone step me through how this goes about executing? I really want to understand this.

Thanks!

1

There are 1 answers

1
Basil Bourque On

String#hashCode

Your email and name variables each hold references to a String object. The String class has its own implementation of hashCode.

To quote the Javadoc for String#hashCode:

Returns a hash code for this string. The hash code for a String object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

So, calling email.hashCode() or name.hashCode() is calling a different hashCode method on a different class rather than your hashCode method in your class.