当前位置:网站首页>Understand why we should rewrite the equals method and hashcode method at the same time + example analysis
Understand why we should rewrite the equals method and hashcode method at the same time + example analysis
2022-07-25 09:25:00 【Work hard, work hard, gzc】
One 、 Let's meet first Java Self contained equals Methods and hashCode Method , Both are Object Class , Source code is as follows :
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
hashCode Method by native modification , It shows that it is a local method , It is from C or C++ Write a method
equals The bottom layer of the method can be seen through == To achieve , So it actually compares whether the references of two objects are equal , That is, whether the memory addresses pointed to by the two are the same .
Two 、 Why rewrite at the same time equals Methods and hashCode Method
First of all, let's talk about rewriting equals Purpose of method : For example, there are two new Coming out Student object A and B, All field attribute values of the two objects are exactly the same ( name 、 Age 、 Unique identification, etc ), At this time, although the memory addresses of the two are different , But the contents of the two are exactly the same , We think they are exactly the same , It's the same object . If you do not override equals Method , Obviously because A and B The memory address of is different , The comparison result is naturally false, We cannot achieve our expected results true, So we're going to rewrite it equals Method so that when the contents of two objects are exactly the same , We will assume that their two quotations are equal , That is, two identical objects , No longer care whether their memory addresses are the same .
Then return to the text ——
Why rewrite at the same time equals Methods and hashCode Methods? ? The analysis is as follows :
In rewriting equals Method , The above two objects A and B Due to different memory addresses , Then don't rewrite hashCode When the method is used , Of the two hash The value must be different . But when we use sets , Such as HashSet、HashMap Duplicate values are not allowed . If you do not override hashCode Method , For example, according to HashMap Access mechanism of collection ( First, according to hash Value determines the position , recycling equals Method to compare whether the accessed objects are equal ),A and B Obviously, they can be stored in the collection , However A and B The content is the same , This violates the principle that the set content cannot be repeated , So we have to rewrite hashCode Method to make two objects with the same value belonging to the same class ( As in this article A and B) Of Hash The values are equal , This ensures that the same content will not be accessed in the collection .
3、 ... and 、 The example analysis
Let's do an experiment , Use the same Student Class to create two instance objects , Then compare the various situations , Whether the two objects are equal .
1、 First the Student Medium hashCode() Method commented out
package com;
import java.util.Objects;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
super();
}
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
/* @Override public int hashCode() { return Objects.hash(age, name); }*/
}
Perform the following tests :
package com.school.eution.accommodation;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Student s1 = new Student(1," Ha ha ha ");
Student s2 = new Student(1," Xi xi xi ");
Map<Object,String> testMap = new HashMap<Object,String>();
testMap.put(s1, " American students ");
System.out.println(s1.hashCode());
System.out.println(testMap.get(s1));
System.out.println("------------------");
System.out.println(s2.hashCode());
System.out.println(testMap.get(s2));
System.out.println("------------------");
System.out.println(s1.equals(s2));
}
}
The results are consistent after multiple runs :
971848845
American students
------------------
1910163204
null
------------------
true
explain : If you do not override hashCode Method will be used from Object Inherited local hashCode() Method , So put the object s1 Put in Map In the after , adopt s1 Objects can be from Map Take out the string “ American students ”, however s2 and s1 Equal in value , But can't use s2 Objects from Map The same value is also obtained in . This is because there is no rewriting hashCode Method , Lead to s1 and s2 Use the default hasCode Methods produce Hash Caused by inconsistent values . therefore s2 When I evaluate it , according to s2 Of hash value “1910163204” Naturally Map I can't find it in .
But if you don't use Map Value , Directly through equals Compare s1 and s2 It's equal ( It is not rewritten at this time hashCode).
Map The value is obtained by hash Value positioning , If hash Value lies in Map in , also hash If the values are consistent, it means that Map In the same linked list of , Continue to use equals Method to compare whether the values are equal , If hash Values are inconsistent , There is no need to compare down and return directly false.
Next Student In a new way hash Code release for
package com;
import java.util.Objects;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
super();
}
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
}
Run the results again :
2321474
American students
------------------
2321474
American students
------------------
true
It's not hard to find out , Even if s2 I didn't ask Map In the store , Because we rewritten hashCode Method , bring s1 and s2 The hash value of is the same , And now s1 And s2 The field attribute values of are equal , therefore s2 We can use s1 Store in Map From the value in . like s1 And s2 Took the same key (key). adopt equals Methods to compare s1 And s2 It is still the same .
summary : Why must we rewrite it at the same time hashCode() Methods and equals() Method :
This is actually aimed at HashSet and HashMap Wait for this kind of use hash For objects whose values are stored . such as : In the HashSet Deposit Student when , If you don't rewrite it hashCode, Go at this time HashSet In the store s1、s2 In fact, it can be saved , Even if s1 And s2 The values of are exactly the same , This obviously violates the principle that the same content cannot be stored in the set .
In addition, if you can't use these Hash Of the collection , Rewrite only equals() Method can also satisfy the comparison of whether the contents of two objects are equal .
边栏推荐
- C#语言和SQL Server数据库技术
- 通过robocopy对文件/夹进行复制
- [WSN communication] optimize HWSN energy-saving clustering protocol based on MATLAB biogeography [including Matlab source code, 1989]
- OpenCV实现简单的人脸追踪
- Difference between redis and mongodb (useful for interview)
- 有误差的字符串型时间比较方法String.compareTo
- 分享一个避免递归的部门设计方法
- 28.插槽
- jsPDF生成PDF文件,文件不全问题,后台进行文件下载,前台不下载
- 使用nexus3发布yum私服(离线-内网)
猜你喜欢

ActiveMQ -- JDBC Journal of persistent mechanism
![[buuctf-n1book][Chapter 2 advanced web]ssrf training](/img/29/8894d04b27e0e73c4458c27bd9b935.png)
[buuctf-n1book][Chapter 2 advanced web]ssrf training

在Ubuntu中安装MySQL并创建新用户

保姆级Scanner类使用详解

『每日一问』简单聊聊JMM/说说对JMM的了解

sqli-labs Basic Challenges Less11-22

Nacos启动报错Unable to start web server

Ten thousand words long, one word thoroughly! Finally, someone has made business intelligence (BI) clear
![[arm] Xintang nuc977 transplants wk2124 drive](/img/0c/fa21d7a44e0263dde4d3135a78818f.png)
[arm] Xintang nuc977 transplants wk2124 drive

Uniapp intercepts route jumps through addinterceptor to control whether the page needs to log in
随机推荐
nacos2.1.0集群搭建
activemq--消息重试机制
保姆级Scanner类使用详解
Arrange the array into the smallest number
Comments on specific applications of camera
In mysql, update and select are used together
28.插槽
excl批量导入数据,后台公共解析方法
@Scheduled源码解析
What is the difference between mongodb and redis
Analysis of concat and group in MySQL_ Use of concat
分享一个避免递归的部门设计方法
神经网络方法——美国波士顿房价(回归问题)
Redis operation uses cursor instead of keys
Flask SSTI注入学习
TCP网络应用程序开发流程
C#语言和SQL Server数据库技术
Activemq-- asynchronous delivery
Kubedm introduction
DVWA练习一 暴力破解