public int hashCode() {
        int sum = width + height;
        return sum * (sum + 1)/2 + width;
    }

解决方案 »

  1.   

    如果写成width+height或者width*height那么Dimension(3,4)和Dimension(4,3)的hashCode就都一样了假设采用hashCode = ((非0 * 质数) + width) * 质数 + height的话,由于width height都只出现一次,可能还是比较容易重复的吧
      

  2.   

    楼上的有道理
    hascode不能重复的吧
      

  3.   

    关于hashCode重复的问题a.equals(b) --> a.hashCode() == b.hashCode()
    但是a.hashCode() == b.hashCode() -/-> a.equals(b)
      

  4.   

    但是        int sum = width + height;
            return sum * (sum + 1)/2 + width;
    为什么能满足hashcode尽量不重复的要求?这里面有什么数学定理或数学常识吗?
      

  5.   

    Sun 的文档是这样说的
    If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. 
    It is not required that if two objects are unequal according to the equalsmethod, then the two objects must produce distinct hash code.
    当你实现了equals的时候,一定要同时生成hashCode,并且当对象相等hashcode也应该相等.
    hashcode主要用在散列的时候对查询等效率影响较大,所以如果生成的hashcode 很容易重复的话,一个由你的对象所组成的HashMap(HashTable)效率就会非常的低.至于hashCode采用什么方法生成并没有特殊规定,只要满足上边几个条件就行了.
      

  6.   

    我只想明白了一点,而非全部首先,sum 和 sum + 1之间的最大公约数只会是1同时sum, sum + 1之中肯定一奇一偶,sum * (sum + 1) / 2也就是一个奇数和那个偶数的一半,他们之间的最大公约数也是1