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