Object–hashCode()


 hashCode()

Object--hashCode()

 1 /**
 2      * Returns a hash code value for the object. This method is
 3      * supported for the benefit of hash tables such as those provided by
 4      * {@link java.util.HashMap}.
 5      * <p>
 6      * The general contract of {@code hashCode} is:
 7      * <ul>
 8      * <li>Whenever it is invoked on the same object more than once during
 9      *     an execution of a Java application, the {@code hashCode} method
10      *     must consistently return the same integer, provided no information
11      *     used in {@code equals} comparisons on the object is modified.
12      *     This integer need not remain consistent from one execution of an
13      *     application to another execution of the same application.
14      * <li>If two objects are equal according to the {@code equals(Object)}
15      *     method, then calling the {@code hashCode} method on each of
16      *     the two objects must produce the same integer result.
17      * <li>It is <em>not</em> required that if two objects are unequal
18      *     according to the {@link java.lang.Object#equals(java.lang.Object)}
19      *     method, then calling the {@code hashCode} method on each of the
20      *     two objects must produce distinct integer results.  However, the
21      *     programmer should be aware that producing distinct integer results
22      *     for unequal objects may improve the performance of hash tables.
23      * </ul>
24      * <p>
25      * As much as is reasonably practical, the hashCode method defined by
26      * class {@code Object} does return distinct integers for distinct
27      * objects. (This is typically implemented by converting the internal
28      * address of the object into an integer, but this implementation
29      * technique is not required by the
30      * Java&trade; programming language.)
31      *
32      * @return  a hash code value for this object.
33      * @see     java.lang.Object#equals(java.lang.Object)
34      * @see     java.lang.System#identityHashCode
35      */
36     public native int hashCode();

View Code

Object--hashCode()

返回这个对象哈希码的值,支持这种方法是为了方便使用哈希表 –比如java.util.HashMap。

Object--hashCode()

下面是hashCode约定的内容:

(1)在应用程序的执行期间,只要对象的equals方法的比较操作所用到的信息没有被修改,那么对同一个对象调用多次,hashCode方法都必须始终如一地返回同一个整数。在同一个应用程序的多次执行过程中,每次执行所返回的整数可以不一致。

(2)如果两个对象根据equals(Object)方法比较是相等的,那么在两个对象上分别调用hashCode()必须产生相同的整数结果。

(3)没有要求说如果两个对象根据equal()方法比较是不相等的,那么在两个对象上分别调用hashCode()产生的整数结果一定不相等。但是,程序员应该意识到,为不相等的对象产生不同的整数结果可以提高散列表的性能。

Object--hashCode()

为了尽可能的实用,Object定义的hashCode方法,对于不同的对象返回的是不同的整数值(这通常是通过将对象的内部地址转换为整数来实现的,但是并非是由Java语言技术实现的)。

 

原创文章,作者:wure,如若转载,请注明出处:https://blog.ytso.com/278584.html

(0)
上一篇 2022年8月3日
下一篇 2022年8月3日

相关推荐

发表回复

登录后才能评论