我不明白为什么 HashSet 在下一个例子中返回 false。代码:
import java.util.*;
public class Name {
private String first, last;
public Name(String first, String last){
this.first = first;
this.last = last;
}
public boolean equals(Name n){
return n.first.equals(first) && n.last.equals(last);
}
public int hashCode(){
return 31*first.hashCode()+last.hashCode();
}
public static void main(String[] args){
Set<Name> s = new HashSet<Name>();
Name n1 = new Name("Donald", "Duck");
Name n2 = new Name("Donald", "Duck");
s.add(n1);
System.out.print("HashCodes equal: ");
System.out.println( n1.hashCode() == n2.hashCode());
System.out.print("Objects equal: ");
System.out.println( n1.equals(n2) );
System.out.print("HashSet contains n1: ");
System.out.println(s.contains(n1));
System.out.print("HashSet contains n2: ");
System.out.println(s.contains(n2));
}
}
结果:
HashCodes equal: true
Objects equal: true
HashSet contains n1: true
HashSet contains n2: false
摘自 HashSet包含方法说明:
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
问题:为什么两个对象都返回 false,即使它们都不为空并且在 hesh 和值方面都相等?
最佳答案
因为您没有覆盖从Object
类继承的equals
方法。
@Override
public boolean equals(Object o){
Name n = (Name)o;
return n.first.equals(first) && n.last.equals(last);
}
输出(演示 here ):
HashCodes equal: true
Objects equal: true
HashSet contains n1: true
HashSet contains n2: true
关于java - Simple HashSet 包含误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266649/