我不明白爲什麼HashSet爲下一個示例返回false。代碼:Simple HashSet包含誤解
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摘錄contains方法說明:
返回true,如果此set包含指定的元素。更多 在形式上返回true,當且僅當此集合包含一個元素e ,使得(o == null?e == null:o.equals(e))。
問題:爲什麼它會爲兩個對象返回false,即使它們都不爲null,並且它們在hesh和value方面都相等?
是的好吧很容易檢查使用:n1.equals((Object)n2)。謝謝! –