现在的位置: 首页 > 综合 > 正文

Effective Java Item9-在覆盖equals方法的同时覆盖hashCode

2013年09月08日 ⁄ 综合 ⁄ 共 3973字 ⁄ 字号 评论关闭

Effective Java 2nd Edition Reading Notes

Item9: Always override hashCode when overrideing equals

在覆盖equals方法的同时覆盖hashCode

 

每当覆盖equals方法的时候,一定要覆盖hashCode方法。

如果没有如此做的话,那么将违反hashCode方法的规范,并导致与基于Hash值的类操作时发生错误。例如HashSetHashTableHashMap

Object#hashCode()的说明如下:

public int hashCode()

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

 

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

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 equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

 

1.       如果同一个对象的在equals中使用的属性没有发生变化,那么在一个java应用程序执行期间,对其调用hashCode返回的结果必须是相同的整数。

2.       如果两个对象的equals方法返回true,那么它们的hashCode方法必须返回相同的整数结果。反之不然。

3.       Object类定义的hashCode方法为特定的对象返回特定的整数。

 

所以,如果覆盖了equals方法而没有覆盖hashCode方法将违反第二条规定,equal objects have equal hashcode.如果两个对象通过覆盖equals方法在逻辑上相等,但是对于hashCode而言,它们是两个独立的对象,没有任何的共同之处。所以hashCode只是返回两个不同的整数。

例如在下面的例子中,只覆盖了equals方法,而没有覆盖hashCode方法,导致在从HashMap中获取key对应的value时获取不到:

package com.googlecode.javatips4u.effectivejava.object;

import java.util.HashMap;

import java.util.Map;

public class OverrideHashCode {

       public static final class PhoneNumber {

              private final short areaCode;

              private final short prefix;

              private final short lineNumber;

              public PhoneNumber(int areaCode, int prefix, int lineNumber) {

                     rangeCheck(areaCode, 999, "area code");

                     rangeCheck(prefix, 999, "prefix");

                     rangeCheck(lineNumber, 9999, "line number");

                     this.areaCode = (short) areaCode;

                     this.prefix = (short) prefix;

                     this.lineNumber = (short) lineNumber;

              }

              private void rangeCheck(int arg, int max, String name) {

                     if (arg < 0 || arg > max)

                            throw new IllegalArgumentException(name + ": " + arg);

              }

              @Override

              public boolean equals(Object o) {

                     if (o == this)

                            return true;

                     if (!(o instanceof PhoneNumber))

                            return false;

                     PhoneNumber pn = (PhoneNumber) o;

                     return pn.lineNumber == lineNumber && pn.prefix == prefix

                                   && pn.areaCode == areaCode;

              }

              // Broken - no hashCode method!

       }

       public static void main(String[] args) {

              Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>();

              PhoneNumber pn = new PhoneNumber(707, 867, 5309);

              m.put(pn, "Jenny");

              String jenny = m.get(pn);

              String jennyNull = m.get(new PhoneNumber(707, 867, 5309));

              System.out.println(jennyNull);

              System.out.println(jenny);

       }

}

虽然new PhoneNumber(707,867,5309)pnequal的,但是由于没有覆盖hashCode,导致使用pn以外的key获取value时,返回null

HashMapput方法和get方法如下:

    public V put(K key, V value) {

       if (key == null)

           return putForNullKey(value);

        int hash = hash(key.hashCode());

        int i = indexFor(hash, table.length);

        for (Entry<K,V> e = table[i]; e != null; e = e.next) {

            Object k;

            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

                V oldValue = e.value;

抱歉!评论已关闭.