java equals重写原则_java中为何重写equals时必须重写hashCode方法详解
前言
大家都知道,equals和hashcode是java.lang.Object类的两个重要的方法,在实际应用中常常需要重写这两个方法,但至于为什么重写这两个方法很多人都搞不明白。
在上一篇博文Java中equals和==的区别中介绍了Object类的equals方法,并且也介绍了我们可在重写equals方法,本章我们来说一下为什么重写equals方法的时候也要重写hashCode方法。
先让我们来看看Object类源码
/**
* 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}.
*
* The general contract of {@code hashCode} is:
*
*
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.
*
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.
*
It is not 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.
*
*
* 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™ 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();
/**
* Indicates whether some other object is "equal to" this one.
*
* The {@code equals} method implements an equivalence relation
* on non-null object references:
*
*
It is reflexive: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
*
It is symmetric: 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}.
*
It is transitive: 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}.
*
It is consistent: 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.
*
For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
*
*
* 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}).
*
* 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);
}
hashCode:是一个native方法,返回的是对象的内存地址,
equals:对于基本数据类型,==比较的是两个变量的值。对于引用对象,==比较的是两个对象的地址。
接下来我们看下hashCode的注释
1.在 Java 应用程序执行期间,在对同一对象多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改。
从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。
2.如果根据 equals(Object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。
3.如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么两个对象不一定必须产生不同的整数结果。
但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。
从hashCode的注释中我们看到,hashCode方法在定义时做出了一些常规协定,即
1,当obj1.equals(obj2)为 true 时,obj1.hashCode() == obj2.hashCode()
2,当obj1.equals(obj2)为 false 时,obj1.hashCode() != obj2.hashCode()
hashcode是用于散列数据的快速存取,如利用HashSet/HashMap/Hashtable类来存储数据时,都是根据存储对象的hashcode值来进行判断是否相同的。如果我们将对象的equals方法重写而不重写hashcode,当我们再次new一个新的对象的时候,equals方法返回的是true,但是hashCode方法返回的就不一样了,如果需要将这些对象存储到结合中(比如:Set,Map ...)的时候就违背了原有集合的原则,下面让我们通过一段代码看下。
/**
* @see Person
* @param args
*/
public static void main(String[] args)
{
HashMap map = new HashMap();
Person p = new Person("jack",22,"男");
Person p1 = new Person("jack",22,"男");
System.out.println("p的hashCode:"+p.hashCode());
System.out.println("p1的hashCode:"+p1.hashCode());
System.out.println(p.equals(p1));
System.out.println(p == p1);
map.put(p,888);
map.put(p1,888);
map.forEach((key,val)->{
System.out.println(key);
System.out.println(val);
});
}
equals和hashCode方法的都不重写
public class Person
{
private String name;
private int age;
private String sex;
Person(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
}
p的hashCode:356573597
p1的hashCode:1735600054
false
false
com.blueskyli.练习.Person@677327b6
com.blueskyli.练习.Person@1540e19d
只重写equals方法
public class Person
{
private String name;
private int age;
private String sex;
Person(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
@Override public boolean equals(Object obj)
{
if(obj instanceof Person){
Person person = (Person)obj;
return name.equals(person.name);
}
return super.equals(obj);
}
}
p的hashCode:356573597
p1的hashCode:1735600054
true
false
com.blueskyli.练习.Person@677327b6
com.blueskyli.练习.Person@1540e19d
equals和hashCode方法都重写
public class Person
{
private String name;
private int age;
private String sex;
Person(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
@Override public boolean equals(Object obj)
{
if(obj instanceof Person){
Person person = (Person)obj;
return name.equals(person.name);
}
return super.equals(obj);
}
@Override public int hashCode()
{
return name.hashCode();
}
}
p的hashCode:3254239
p1的hashCode:3254239
true
false
com.blueskyli.练习.Person@31a7df
我们知道map是不允许存在相同的key的,由上面的代码可以知道,如果不重写equals和hashCode方法的话会使得你在使用map的时候出现与预期不一样的结果,具体equals和hashCode如何重写,里面的逻辑如何实现需要根据现实当中的业务来规定。
总结:
1,两个对象,用==比较比较的是地址,需采用equals方法(可根据需求重写)比较。
2,重写equals()方法就重写hashCode()方法。
3,一般相等的对象都规定有相同的hashCode。
4,String类重写了equals和hashCode方法,比较的是值。
5,重写hashcode方法为了将数据存入HashSet/HashMap/Hashtable(可以参考源码有助于理解)类时进行比较
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
java equals重写原则_java中为何重写equals时必须重写hashCode方法详解相关推荐
- java 取对象的类_Java中通过Class类获取Class对象的方法详解
前言 本文主要给大家介绍的是关于Java通过Class类获取Class对象的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: 阅读API的Class类得知,Class 没有公共 ...
- java json解析 代码_Java构造和解析Json数据的两种方法详解一
在www.json.org上公布了很多JAVA下的json构造和解析工具,其中org.json和json-lib比较简单,两者使用上差不多但还是有些区别.下面首先介绍用json-lib构造和解析Jso ...
- java增强for循环_Java中增强for循环的实现原理和坑详解
前言 引入增强for循环的原因:在JDK5以前的版本中,遍历数组或集合中的元素,需要先获得数组的长度或集合的迭代器,比较麻烦. JDK5中定义了一种新的语法----增强for循环,以简化此类操作.增强 ...
- Java基础提升篇:equals()与hashCode()方法详解
概述 java.lang.Object类中有两个非常重要的方法: public boolean equals(Object obj) public int hashCode() Object类是类继承 ...
- python反向缩进_在Pycharm中对代码进行注释和缩进的方法详解
在Pycharm中对代码进行注释和缩进的方法详解 一.注释 1. #单行注释 2. """ 多行注释 """ 3. pycharm多行注释快 ...
- python二维元组_python中读入二维csv格式的表格方法详解(以元组/列表形式表示)
如何去读取一个没有表头的二维csv文件(如下图所示)? 并以元组的形式表现数据: ((1.0, 0.0, 3.0, 180.0), (2.0, 0.0, 2.0, 180.0), (3.0, 0.0, ...
- python可以使用二维元组吗_python中读入二维csv格式的表格方法详解(以元组/列表形式表示)...
怎么去读取一个没有表头的二维csv文件(如下图所示)? 并以元组的形式表现数据: ((1.0, 0.0, 3.0, 180.0), (2.0, 0.0, 2.0, 180.0), (3.0, 0.0, ...
- python元组读取到列表_python中读入二维csv格式的表格方法详解(以元组/列表形式表示)...
如何去读取一个没有表头的二维csv文件(如下图所示)? 并以元组的形式表现数据: ((1.0, 0.0, 3.0, 180.0), (2.0, 0.0, 2.0, 180.0), (3.0, 0.0, ...
- python 读取图片转换为一维向量_对Python中一维向量和一维向量转置相乘的方法详解...
对Python中一维向量和一维向量转置相乘的方法详解 在Python中有时会碰到需要一个一维列向量(n*1)与另一个一维列向量(n*1)的转置(1*n)相乘,得到一个n*n的矩阵的情况.但是在pyth ...
- thinkphp3.1.3 getshell_C# / VB.NET 在PPT中创建、编辑PPT SmartArt图形的方法详解_C#教程...
本文介绍通过C#和程序代码来创建和编辑PPT文档中的SmartArt图形.文中将分两个操作示例来演示创建和编辑结果. 使用工具:Spire.Presentation for .NET hotfix 5 ...
最新文章
- python爬虫之微打赏(scrapy版)
- Error:Unable to resolve target android-19
- DataSet的数据并发异常处理
- bufferedimage生成的图片模糊_Kaptcha图片验证码工具
- js 方法传递对象参数
- (82)FPGA竞争与冒险-面试必问(六)(第17天)
- STM32--MPU内存保护单元(二)
- Git学习之路(6)- 分支操作
- [USACO10MAR]伟大的奶牛聚集
- UVA11752 The Super Powers —— 数论、枚举技巧
- raid1与raid5
- 随机森林模型解释_随机森林解释
- 计算机 ppt图标,史上最完整的通信计算机PPT图标及模版 (PPTshare).ppt
- C++并发编程(7):条件变量(conditional variable)、wait( )与notify_one( )、spurious wakeups(虚假唤醒)
- 3 staruml 流程图,staruml流程图(staruml怎么画顺序图)
- 电子技术基础(三)__电感的感抗_无功功率和电容的容抗_无功功率
- 简单实用:可以祛斑的食物 - 生活至上,美容至尚!
- 什么是BI、数据仓库、数据湖和数据中台,他们有什么差异?
- JAVA算术右移与无符号右移
- win10系统电脑声音图标正常,但没有声音