AIP解释:
如果此 set 中尚未包含指定元素,则添加指定元素。更正式地说,如果此 set 没有包含满足 (e==null ? e2==null : e.equals(e2)) 的元素 e2,则向此 set 添加指定的元素 e。如果此 set 已包含该元素,则该调用不更改 set 并返回 false。 英文版:
 * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.import java.util.HashSet;public class Myobj{
  public boolean equals(Object obj){
    return true;
  }
  public static void main(String[] args) {
    Myobj a=new Myobj();
    Myobj b=new Myobj();
    HashSet ts=new HashSet();
    ts.add(a);
    ts.add(b);
    System.out.println(ts.size());
  }
}
问题是: equals 返回的是 true了, 为什么能再次添加进去呢?PS: 重写 当hashcode()返回值相同的时候,才不会插入。那么,API的解释是不是疏忽了?那也就是 add的时候,是通过 hashcode来比较的?
问题又来了, 当 hashcode返回值一致,但是 equals()返回 flase的时候。
add是成功的。 也就是 hashSet.add() 不是单纯的调用 hashcode()..
是先调用 equals(),然后再调用 hashcode()?
为什么要这样呢? 直接调研hashcode() 或者equals()不是更好?
两个一起调用的必要性在哪里?为什么hashSet.add()上面 强调的是 equals 却疏忽 hashcode?

解决方案 »

  1.   

    楼主:
    hashCode 的常规协定是: 如果根据 equals(Object) 方法,两个对象是相等的,那么在两个对象中的每个对象上调用 hashCode 方法都必须生成相同的整数结果。euqals 相同,hashCode 不同的情况本身就不规范,是编程过程要避免出现的。
      

  2.   

    Myobj a=new Myobj();
    Myobj b=new Myobj();
    这么写 你写多少个能插多少个 a 和 b 不是同块内存地址 
    Myobj a  = b 你再试试
      

  3.   

    为什么不能,都是NEW出来的,内存地址肯定不一样啊。。
      

  4.   

     equals相等,比的是内存中的hashcode,这个方法和equals都要重写。你equals方法重写的不太正确,不管传什么,都对。不太规范。你判断他们是否equals的时候是比较这个引用的hashcode;为什么hashSet.add()上面 强调的是 equals 却疏忽 hashcode?hashcode主要用来索引判断的,在MAP中用的比较多。
    class Name{
        private String firstName,lastName;
        public Name(String firstName, String lastName) {
            this.firstName = firstName; this.lastName = lastName;
        }
        public String getFirstName() {  return firstName;   }
        public String getLastName() {   return lastName;   }
        public String toString() {  return firstName + " " + lastName;  }
        
        public boolean equals(Object obj) {
        if (obj instanceof Name) {
            Name name = (Name) obj;
            return (firstName.equals(name.firstName))
                && (lastName.equals(name.lastName));
        }
        return super.equals(obj);
    }
    public int hashCode() {
        return firstName.hashCode();
    }
    }
      

  5.   

    重写equals方法必须重写hashcode,这是常识。原因 上面的人都说了。强调下,判断2个对象是否是相同,首先是要求重写equals方法---》这是用来判断的方法,必须重写。其次,还要求重写hashcode方法。这有点类似你定义规则。equals方法里,必须和hashcode方法规则逻辑一致性---》拿来判断的属性一样。
     如果看不懂,建议看下String的equals和hashcode方法