首页 > 代码库 > True or False? and WHY??? Java HashSet Contains

True or False? and WHY??? Java HashSet Contains

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