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.