I'm doing a school assignment where I need to store a bunch of contacts. Each contact has a HashSet of social network accounts, addresses and phone numbers.
I DO NOT want to store multiple copies of the same object in my HashSet, so I have overridden the hashCode() and equals() method for each object.
But for my social network account object only,my HashSet is storing the same object twice!
I have two different objects:
SocialNetworkAccount s1 = new SocialNetworkAccount(SocialNetworkAccount.AccountType.FACEBOOK, "wallcrawler123");
SocialNetworkAccount s2 = new SocialNetworkAccount(SocialNetworkAccount.AccountType.FACEBOOK, "wallcrawler123");
s1.equals(s2) returns true and s1.hashCode() == s2.hashCode() returns true, but s1 == s2 returns false! Why?
This is the hashCode() method I'm using:
public int hashCode() {
int prime = 31;
int result = 1;
result = result*prime + type.hashCode();
result = result*prime + id.hashCode();
return result;
}