HashCode()

1、首先,hashcode()是Object类自带的方法,是个native 方法,而且返回的是一个int类型的值。
/**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code 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.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code 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 hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code 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
     * Java<font size="-2"><sup>TM</sup></font> programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
 public native int hashCode();**

2、在Object类中,hashCode()返回的并不是对象在内存中的物理存储地址,而(或许)是根据内存物理地址以及对象的相关信息计算出的一个int 型值。(说明:1)、这里为什么会与物理地址相关,个人无法给出证据(真心求大神指教);2)、为什么与对象相关,是根据哈希算法,为每个对象提取一个关键值)。

3、在Object的子类中大多都重写了改方法,重写的目的是让调用该对象者最终对该对象的存储时能在整个存储空间能够等概率、均匀分布(即hashcode()的作用),而反过来理解,通过hashcode()计算出来的值成为了该对象的一个特征(不同对象的哈希值可能相同)。例如String类中对该方法的重写:

/**
     * Returns a hash code for this string. The hash code for a
     * <code>String</code> object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using <code>int</code> arithmetic, where <code>s[i]</code> is the
     * <i>i</i>th character of the string, <code>n</code> is the length of
     * the string, and <code>^</code> indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

例子如下:

public class Test {

    public static void main(String[] args){

        String a = new String("aw");
        String b = new String("c9");
        System.out.println(a==b);
        System.out.println("a 的哈希码:  "+a.hashCode());
        System.out.println("b 的哈希码:  "+b.hashCode());
    }
}

结果如下:

false
a 的哈希码:  3126
b 的哈希码:  3126

从上可知,不同的对象,hashcode()可能相等的,这也就有了hash表的冲突解决问题,有了对象相等比较时的equals()问题。

4、子类为什么需要重写hashcode方法?
一般重写hashcode的子类都是需要用到哈希算法来检索元素的哈希地址。此时,比如HashMap里面,hashcode的功能是时让同一个Entry实体根据其key及value就能确定存储在哪个范围,这跟实现hashmap这一功能的具体思想有关。
假如不实现hashcode方法,那么里面调用到hashcode时必然会调用父类(最原始为Object类)的hashcode()。情景一:两对象根据算法的实现要求本来哈希值应该相等,但是因调用父类的hashcode方法,也许就不等了,这与原理就相违背了;情景二,例如在HashMap中,根据indexFor(hash, table.length)可以直接将Entry定位到buckt的具体指针处。而hash()如下:

final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

再来看看hashcode是如何重写的:

public final int hashCode() {
  return Objects.hashCode(getKey())                     ^Objects.hashCode(getValue());
        }

如果hashcode不重写,又如何能实现准确定位呢?父类可不知道你有key和value这么个东西的存在。所以说,重写hashcode就是为了根据业务需求,为自己量身打造的重要一步。

参考:
http://www.cnblogs.com/dolphin0520/p/3681042.html(浅谈java hashcode)
http://www.cnblogs.com/jiewei915/archive/2010/08/09/1796042.html(哈希表)
http://blog.csdn.net/liushuai_ly/article/details/8197508(hashcode重写的必要性)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值