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!
String#hashCodeYour
emailandnamevariables each hold references to aStringobject. TheStringclass has its own implementation ofhashCode.To quote the Javadoc for
String#hashCode:So, calling
email.hashCode()orname.hashCode()is calling a differenthashCodemethod on a different class rather than yourhashCodemethod in your class.