当HashSet调用相等的方法? [英] When HashSet call equal method?
问题描述
我在一个教程中找到了这个例子。
I found this example in one tutorial .
当我运行它时,我得到hs.size()值为2 ..并且equals方法只调用一次任何人在equal()方法调用时解释我在HashSet中
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
推荐答案
您的代码将调用等于<$ code>
HashTest
只有一次。另一次它调用 equals()
方法将是的
class。等于()
字符串
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
这个答案说明 HashSet $ c调用
equals()
方法的时间$ c>什么时候不是。摘录自:
This answer explains when the equals()
method is called by the HashSet
and when it isn't. An excerpt from it:
HashSet利用哈希码来加快速度。它假设两个相等的对象将具有相同的哈希码。但是,它并不假设具有相同哈希码的两个对象意味着它们是相等的。这就是为什么当它检测到冲突的哈希码时,它只会与具有相同哈希码的集合中的其他对象(在您的情况下为一个)进行比较。
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.
这篇关于当HashSet调用相等的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!