In my most recent question, I was informed that I needed to override my equals
and hashcode
method (among other things). So I took a bit of time to read a few articles and attempted to come up with a proper implementation.
Here are some of the articles I read:
- Hashcode on Wikipedia
- StackOverflow Overriding equals and hashcode
- StackOverflow Why does hashcode use multiplier 31
All the articles were pretty good. Since this is my first time attempting to do this, I just want to be sure I'm not making some simple (or dumb) mistake.
I will be using name
to indicate whether my Person
object is equivalent to another Person
object. The reason for this, is that all the other variables can vary, but the name will always be unique.
Updated to reflect recommended changes
public class Person {
private String name;
private int p_number;
private String address;
//other variables
public Person(String a_name) {
name = a_name;
}
public String getName() {
return name;
}
//other getters and setters
@Override
public boolean equals(Object o) {
if(o == null)
return false;
if(o == this)
return true;
if(!(o instanceof Person))
return false;
Person p = (Person) o;
return name.equals(p.name));
}
@Override
public int hashCode() {
return name.hashCode();
}
}
My questions are as follows:
- Did I implement these methods correctly?
- Since
name
is the only variable that determines uniqueness, do I need to bother checking any of the other variables inhashcode
? - I was reading on StackOverflow that 31 was chosen as a good prime number awhile ago, but choosing a larger prime is better now? Can someone confirm or deny this claim? (the claim was made in the third link above)
If I haven't implemented these methods properly, how can I change/improve them?