標籤:note use 原因 man java imp bsp 一段 elements
import java.util.HashSet; public class MyClass { public String s; public MyClass(String s) { this.s = s; } public int hashCode() { return s.hashCode(); } public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof MyClass)) return false; MyClass other = (MyClass)obj; if(s == null) { return false; } return(s.equals(other.s)); } public static void main(String[] args) { HashSet<MyClass> set = new HashSet<MyClass>(); MyClass mc1 = new MyClass("a"); set.add(mc1); mc1.s = "b"; MyClass mc2 = new MyClass("b"); if(set.contains(mc2)) { System.out.println("True"); } else { System.out.println("False"); } } }
結果是False
我猜原因是:
在向set儲存時。位置是使用之前的雜湊值得到的。
之後改變了mc1.s使得其雜湊值發生了變化。
調用contains方法時,找的是之後雜湊值指向的位置。這是儘管mc1和mc2有同樣的雜湊值、且true == mc1.equeals(mc2)。但在該位置上根本沒有儲存東西,所以返回false
另外剛才找到Set的API文檔裡有這麼一段話
Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set.
這樣結果是False或許就是由於HashSet的實現方法(用了雜湊散列儲存)~~
True or False? and WHY??? Java HashSet Contains