Java的hashCode方法

 0 Java的hashCode方法概述

    In the Java programming language, every class implicitly or explicitly provides a hashCode() method, which digests the data stored in an instance of the class into a single hash value (a 32-bit signed integer). Technically, in Java, hashCode() by default is a native method, meaning, it has the modifier 'native', as it is implemented directly in the native code in the JVM. (使用native关键字说明这个方法是原生函数,也就是这个方法是用C/C++语言实现的,并且被编译成了DLL,由java去调用。native关键字介绍)
    All the classes inherit a basic hash scheme from the fundamental base class java.lang.Object, but instead many override this to provide a hash function that better handles their specific data. Classes which provide their own implementation must override the object method public int hashCode().

1  Object类的hashCode()

public int hashCode()
返回该对象的哈希码值。支持此方法是为了提高哈希表(例如 java.util.Hashtable 提供的哈希表)的性能。

hashCode 的常规协定是:

  • 在 Java 应用程序执行期间,在对同一对象多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改。从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。
  • 如果根据 equals(Object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。
  • 如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么对这两个对象中的任一对象上调用 hashCode 方法 要求一定生成不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。

实际上,由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。(这一般是通过将该对象的内部地址转换成一个整数来实现的,但是 JavaTM 编程语言不需要这种实现技巧。) 附equals方法和hashCode方法的详解

2  常用类的hashCode()

2.1 Integer类的hashCode()

java.lang.Object
        继承者 java.lang.Number
              继承者 java.lang.Integer
public int hashCode()
     覆盖:类 Object 中的 hashCode
     返回:该对象的哈希码值,它的值即为该Integer对象表示的基本 int 类型的数值

2.2 String类的hashCode()

java.lang.Object
继承者 java.lang.String
public int hashCode()
     覆盖:类 Object 中的 hashCode
     返回:该对象的哈希码值。String 对象的哈希码根据以下公式计算:
                h(s)=sum_{i=0}^{n-1}sleft[\,i\,
ight] cdot 31^{n-1-i}        
即:h(s)=s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1];
     使用int算法,这里s[i]是字符串的第i个字符,n是字符串的长度,^表示求幂。(空字符串的哈希值为0)
 
原文地址:https://www.cnblogs.com/nightowc/p/4674111.html