Java equals 方法与hashcode 方法的深入解析
发布时间:2022-03-05 19:20:15
PS:本文使用jdk1.7
解析
1.Object类 的equals 方法
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
看代码,Object的equals方法,采用== 进行比较,只是比较对象的引用,如果引用的对象相同,那么就返回true.
看注释,Object的equals方法,具有如下特性
1.reflexive-自反性
x.equals(x) return true
2.symmetric-对称性
x.equals(y) return true
y.equals(x) return true
3.transitive-传递性
x.equals(y) return true
y.equals(z) return true
x.equals(z) return true
4.consistent-一致性
x.equals(y) return true //那么不管调用多少次,肯定都是返回true
5.与null的比较
x.equals(null) return false //对于none-null的x对象,每次必然返回false
6.于hashcode的关系
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
需要注意的是,一般来说,如果重写了equals方法,都必须要重写hashcode方法,
来确保具有相同引用的对象,能够具有同样的hashcode值
好了,看到这里,我们就明白了,为什么重写了equals方法,一般来说就需要重写hashcode方法,
虽然这个不是强制性的,但是如果不能保证相同的引用对象,没有相同的hashcode,会对系统留下很大隐患
2.String类的equals方法
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
看源码,我们可以发现,这个比较分为两部分
1.先比较是否引用同一对象
2.如果引用对象不同,是否两个String的content相同
3,String 类的hashcode 方法
/**
* 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;
}
可以看到hashcode的计算公式为:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
因此,对于同一个String,得出的hashcode必然是一致的
另外,对于空的字符串,hashcode的值是0
小结
至此,我们可以对本文开头的疑问做一个小结.
1.字符串比较时用的什么方法,内部实现如何?
使用equals方法,先比较引用是否相同,后比较内容是否一致.
2.hashcode的作用,以及重写equal方法,为什么要重写hashcode方法?
hashcode是系统用来快速检索对象而使用,equals方法是用来判断引用的对象是否一致,所以,当引用对象一致时,必须要确保其hashcode也一致,因此需要重写hashcode方法来确保这个一致性


猜你喜欢
- 1.如下图中的检测值存到数据库是科学计数法2 经过代码处理后3 只需要对你读到的字符串进行如下操作BigDecimal bd = new B
- SpringBoot中的SpringMVC配置功能都是在WebMvcAutoConfiguration类中,xxxxAutoConfigur
- 问题项目是springcloud项目,在maven install某一个项目时报错:程序包com.example.commons.appli
- 引言java 7提供了另外一个很有用的线程池框架,Fork/Join框架理论Fork/Join框架主要有以下两个类组成. * ForkJoi
- 序本文主要研究下在带有lombok(1.16.20版本)注解的代码在java10下的编译问题。问题Fatal error compiling
- Java流程控制用户交互Scannerjava.util.Scanner是Java5的新特征,可以通过Scanner类来获取用户的输入基本语
- 本文实例讲述了C#串口通信实现方法。分享给大家供大家参考。具体方法如下:通过COM1发送数据,COM2接收数据。当COM2接收完本次发送的数
- 最近使用到了maven的profile功能,发现这个功能的确很好用也很实用,这块的知识比较多也比较乱,其实真正理解了之后非常简单,为了巩固总
- 指定创建派生类实例时应调用的基类构造函数;调用基类上已被其他方法重写的方法。注意:不能从静态方法中使用base关键字,base关键字只能在实
- 一、前言前面我们介绍了运算符的一部分运算符,现在我们把剩余的他介绍完全来二、运算符赋值运算符所谓赋值,就是一个等于号连接的两个如int a=
- 一.你了解类吗?在Java中,类文件是以.java为后缀的代码文件,在每个类文件中最多只允许出现一个public类,当有public类的时候
- springMVC项目中实现图形验证码功能,可以使用kaptcha来实现,下面是步骤一、引入架包,pom.xml<dependency
- 前言很久没写BLOG了,之前在写Android聊天室的时候答应过要写一个客户(好友)之间的聊天demo,Android 基于Socket的聊
- 基本思路服务器配置如下:192.168.159.50 gitlab服务器(Gitlab,内存至少5个G,要不根本跑不动)192.168.15
- 帮我们实现各种类型的复杂手势操作。其实例通过静态工厂创建ViewDragHelper一般用在一个自定义ViewGroup的内部。初始化操作
- 我在Eclipse/MyEclipse环境下都测试过了,都好使。需要2个组件,分别是: ext-4.0.2a.jsb2 spke
- 前言这是上周在开发 C# 中使用 Proxy 代理时开发的一些思考和实践。主要需求是这样的,用户可以配置每次请求是否需要代理,用户可以配置
- 这篇文章主要介绍了Spring 自动装配的二义性实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 1、Date日期输出可读性较差Date date = new Date();System.out.println(date);打印输出的结果
- 本文主要介绍的是一个球形水波的百分比控件,市面上有各种形形色色的百分比控件,我一直觉得水波是最炫的,UI给了我这个机会,然而网上搜了一大堆,