1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks so much. But why I should use Object o as parameter instead of Pair o?
Because HashMap compares objects it contains using the equals(Object) method declared on Object, not using the other equals(Pair) method you added to Pair.
I am a little confused about hashCode and equals. In class, we are taught that we use hash code to access element in hashtable. Why here we need to use equals too? Isn't hashCode enough?
No, hashCode() isn't enough. A HashMap is like a cabinet with drawers. When you want to get something from the map, the map first calls hashCode() on your key. That allows it to find the drawer where it stored the object. Then it compoares your key, using equals(), with all the keys stored in the drawer. If it finds one, then the key is in the map, otherwise, it's not. With a good hashCode implementation, there are usually 0, 1 or very few keys per drawer, which makes HashMap very fast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.