Reputation: 191
I want to use HashMap to help count a pair element's number. Here I have a class Pair as follows:
class Pair{
String s1;
String s2;
Pair(String ss1,String ss2) {
s1 = ss1;
s2 = ss2;
}
public int hashCode(){
Integer a = Integer.valueOf(s1);
Integer b = Integer.valueOf(s2);
return 31 * a + b;
}
public boolean equals(Pair c) {
if (c == null) return false;
if (this.s1.equals(c.s1) && this.s2.equals(c.s2)) return true;
return false;
}
}
I applied my Pair class to a HashMap
HashMap<Pair,Integer> map1 = new HashMap<Pair,Integer>();
while (...) {
Pair p = new Pair(word, lastword);
if (map1.get(p) == null) {
map1.put(p,0);
}
map1.put(p,map1.get(p)+1);
}
Although I have defined hashCode and equals function in my Pair class. My code map1.get(p) == null would always be true as if the map never see a pair with two same string. Finally, the output is:
7 , 2 : 1
7 , 2 : 1
7 , 2 : 1
7 , 2 : 1
7 , 2 : 1
7 , 2 : 1
7 , 2 : 1
instead of
7 , 2 : 7
which means my map treats every Pair("7","2") as a different pair although they have the same hash code.
Could anyone tell my where I do wrong in the design of Pair class ?
Thanks.
Upvotes: 1
Views: 4653
Reputation: 691655
Your equals()
method doesn't override Object.equals()
. The proper signature is
@Override
public boolean equals(Object o)
Note the use of @Override
, which tells the compiler that your intention is to override a method. If you don't actually override one (as is the case in your code), the compiler will refuse to compile, and you will thus detect that your signature is incorrect.
Also, if s1
and s2
are supposed to always represent integers, their type should be int
, not String
.
Upvotes: 2