0

I found this example in one tutorial .

when I run this I got hs.size() value is 2 ..and the equals method is called only one time Any one explain me when equal() method calls in HashSet

import java.util.HashSet;

public class HashTest {
    private String str;

    public HashTest(String str) {
        this.str = str;
    }

    @Override
    public String toString() {      
        return str;
    }

    @Override
    public int hashCode() {             
        return this.str.hashCode();
    }

    @Override
    public boolean equals(Object obj) { 
        System.out.println("calling equal method");
        if (obj instanceof HashTest) {

            HashTest ht = (HashTest) obj;
             System.out.println(ht.str);
            return this.str.equals(ht.str);
        }
        else
        {
            System.out.println("Not equal");
        }
        return false;
    }

    public static void main(String args[]) {
        HashTest h1 = new HashTest("1");
        HashTest h2 = new HashTest("1");
        String s1 = new String("2");
        String s2 = new String("2");

        HashSet<Object> hs = new HashSet<Object>();
        hs.add(h1);
        hs.add(h2);
        hs.add(s1);
        hs.add(s2);

        System.out.print(hs.size());
    }
}

when the equal method call in the above program

morgano
  • 17,210
  • 10
  • 45
  • 56
user2963481
  • 2,003
  • 6
  • 19
  • 20
  • 1
    When `a.hashCode() == b.hashCode()`. i.e. `equals` is used to determine whether two objects are the same in the case of a `hashCode` clash. (it would also be used in the `contains` and `remove` methods but you don't use them here). – Boris the Spider Feb 07 '14 at 11:42
  • `equals` will be called twice, but you'll only log one of the calls, since the other call is a String's method. – user2357112 Feb 07 '14 at 11:43

1 Answers1

4

Your code will call the equals() of HashTest only once. The other time it calls the equals() method would be the equals() of the String class.

hs.add(h1); // Nothing is called
hs.add(h2); // Calls the equals() method of HashTest, thus the log
hs.add(s1); // Nothing is called
hs.add(s2); // Calls the equals() method of String

This answer explains when the equals() method is called by the HashSet and when it isn't. An excerpt from it:

The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.

Community
  • 1
  • 1
Rahul
  • 44,383
  • 11
  • 84
  • 103