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

Effective Java 2nd Edition Reading Notes

Item9: Always override hashCode when overrideing equals

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

 

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

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

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)和pn是equal的,但是由于没有覆盖hashCode,导致使用pn以外的key获取value时,返回null。

HashMap的put方法和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;

                e.value = value;

                e.recordAccess(this);

                return oldValue;

            }

        }

 

        modCount++;

        addEntry(hash, key, value, i);

        return null;

    }

 

    public V get(Object key) {

       if (key == null)

           return getForNullKey();

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

        for (Entry<K,V> e = table[indexFor(hash, table.length)];

             e != null;

             e = e.next) {

            Object k;

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

                return e.value;

        }

        return null;

    }

从put和get方法可以得知,HashMap的操作是基于key的hashCode值来进行(添加或者查找)的。

一个简单的实现hashCode方法:

// worst hashCode override implementation

       @Override

       public int hashCode() {

              return 10;

       }

该方法为所有的对象返回相同的hashCode。良好的hashCode应该使unequal对象的hashCode不相同。

如果使用上面的hashCode实现,那么上面的代码的返回值为:

Jenny

Jenny

编写hashCode的一个规范:

1. Store some constant nonzero value, say, 17, in an int variable called result.

2. For each significant field f in your object (each field taken into account by the equals method, that is), do the following:

a. Compute an int hash code c for the field:

i. If the field is a boolean, compute (f?1:0).

ii. If the field is a byte, char, short, or int, compute (int) f.

iii. If the field is a long, compute (int) (f ^ (f >>> 32)).

iv. If the field is a float, compute Float.floatToIntBits(f).

v. If the field is a double, compute Double.doubleToLongBits(f), and then hash the resulting long as in step 2.a.iii.

vi. If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke  hashCode on the field. If a more complex comparison is required, compute a “canonical representation” for this field and invoke hashCode on the canonical representation. If the value of the field is null, return 0 (or some other constant, but 0 is traditional).

vii. If the field is an array, treat it as if each element were a separate field. That is, compute a hash code for each significant element by applying these rules recursively, and combine these values per step 2.b. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5.

b. Combine the hash code c computed in step 2.a into result as follows:

        result = 31 * result + c;

3. Return result.

4. When you are finished writing the hashCode method, ask yourself whether equal instances have equal hash codes. Write unit tests to verify your intuition! If equal instances have unequal hash codes, figure out why and fix the problem.

同时,可以将冗余的字段排除在计算hash code之外。冗余的字段是指可以由其他字段决定的字段。

必须将没有在equals中使用的字段排除在计算hash code之外。因为这可能导致违反hashCode规范2。

使用一个非0的初始hash code。

@Override

public int hashCode() {

       int result = 17;

       result = 31 * result + areaCode;

       result = 31 * result + prefix;

       result = 31 * result + lineNumber;

       return result;

}

 

如果一个类是不可变类,并且计算hashCode的消耗比较大的话,可以将hashCode缓存起来,以免每次都要计算hashCode。如果可以确定类的实例会频繁的作为Map的hash key,那么应该在创建实例的时候就计算hashCode,否则的话就在第一次调用hashCode的时候进行lazy initialize。

@Override

public int hashCode() {

       int result = hashCode;

       if (result == 0) {

              result = 17;

              result = 31 * result + areaCode;

              result = 31 * result + prefix;

              result = 31 * result + lineNumber;

              hashCode = result;

       }

       return result;

}

不要为了追求性能而排除重要属性的hash code计算。 hash code的计算性能将影响到HashTable或者HashMap的效率。


转自:http://blog.csdn.net/sunjavaduke/article/details/4540160

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值