Hashcode的Hashcode和Equals [英] Hashcode and Equals for Hashset
问题描述
请澄清我对Hashset的疑问。请考虑以下代码,
Please clarify my doubt in Hashset. Consider the following code,
class Person
{
String name;
Person(String n)
{
name=n;
}
public String getName()
{
return name;
}
@Override
public boolean equals(Object arg0) {
System.out.println("in equals");
Person obj=(Person)arg0;
System.out.println("1st "+getName());
System.out.println("2nd "+obj.getName());
if(this.getName().equals(obj.getName()))
{
return true;
}
return false;
}
@Override
public int hashCode() {
System.out.println("in hash code");
System.out.println(" value is "+Integer.valueOf(name.charAt(0)));
return Integer.valueOf(name.charAt(0));
}
}
在main我有以下代码
in main I have the following code
Person obj1=new Person("bcd");
Person obj2=new Person("cde");
Person obj3=new Person("abc");
Person obj4=new Person("abc");
现在,如果我将这些对象添加到hashset
Now if I add these objects to hashset
Set<Person> sset=new HashSet<Person>();
sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj3);
我收到此输出
in hash code
value is 98
in hash code
value is 97
in hash code
value is 99
in hash code
value is 97
in equals
1st abc
2nd abc
问题1 :为什么equals()函数只调用一次来检查obj3和obj4?为什么没有检查剩下的对象?
Question 1 : why equals() function is called only once for checking obj3 and obj4 ? Why its not checked for rest of the objects ?
问题2 :如果答案是因为它们都有相同的哈希码,那么只有等于将被调用,然后为什么不调用下面的代码
Question 2 : If the answer is because they both have same hash code,only then equals will be called, then why its not called for below code
sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj4);
输出为:
in hash code
value is 98
in hash code
value is 97
in hash code
value is 99
in hash code
value is 97
即使两个相同的对象,它也不会进入equals()方法被添加到具有相同哈希码的哈希集。
It's not going inside equals() method even though two same objects are added to hash set which has same hash code.
问题3 :我迭代了上面的值并打印了内容但是既没有哈希码也没有等于被称为。当它真的有用来覆盖hashcode和equals方法吗?
Question 3 :I iterated the above value and printed the contents but neither hashcode nor equals were called. when its really useful to override hashcode and equals method ?
问题4 :什么时候 hashCode()
和等于()
被调用?
Question 4 : When will hashCode()
and equals()
be called?
推荐答案
- 如果
hashCode
不同,则无需调用等于
。 - 如果
(obj1 == obj2)
,则无需调用hashCode
。 - 不需要
hashCode
和/或等于
只是为了迭代 - 你不是在比较对象 - 当需要区分对象时。
- There's no need to call
equals
ifhashCode
differs. - There's no need to call
hashCode
if(obj1 == obj2)
. - There's no need for
hashCode
and/orequals
just to iterate - you're not comparing objects - When needed to distinguish in between objects.
这篇关于Hashcode的Hashcode和Equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!