java中的equals方法+hashCode方法

【0】README

0.1)以下内容均为原创,包括源代码, 旨在理清 equals 和 hashCode 方法的 实现原理
0.2) for full resource code, please visit
https://github.com/pacosonTang/core-java-volume/blob/master/chapter13/EqualsHashCodeTest.java

【1】equals 方法

1.1)父类Object中的equals 方法, 它本身比较的就是两个对象的内存地址是否相等(Object.equals 源码):
这里写图片描述
1.2)自定义类中,如果希望对象中各个成员变量 分别相等,则它们的equals 方法 返回 true, 则:
这里写图片描述
这里写图片描述


【2】hashCode 方法(String.hashCode 源码)

这里写图片描述
2.1)而 Object.hashCode 的返回值:
2.2)以下内容转自 API:http://docs.oracle.com/javase/8/docs/api/

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 hash tables.

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 Java™ programming language.)
  • 2.2.1)译文如下:
  • hashCode的常规约定是:
    • 1)对同一个对象的不止一次调用, hashCode 方法必须返回同一个整型值,假如 在equals方法 比较两个对象的过程中 没有信息被修改的话。当对同一个应用的不同执行,这个值(hashCode)不需要保持一致;可以不一样;
    • 2)如果两个对象在 equals 方法中被认为相等, 则 上述两个对象的 hashCode 也应该返回相同的值;
    • 3)不做要求的是,如果 java.lang.Object.equals 认为两个对象不相等,则 两个对象的 hashCode 方法 返回 不同的值。然而, 编码者应该注意的是,对不相等对象产生的不同整型值(hashCode) 可能会影响 哈希表的性能;
  • Object.hashCode 的返回值:(对象的内部地址值)
    • 要做到尽可能合理实用, Object.hashCode 方法对不同的对象产生不同的整型值。(这往往是通过 将对象的内部地址值转换为 整型值来实现的, 但这个实现技术不是 Java 编程语言硬性要求的)。

2.3) 我们再来看 Object.hashCode 的源码:
这里写图片描述
for detailed native keyword , please visit http://blog.csdn.net/pacosonswjtu/article/details/50312333
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值