当前位置:网站首页>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数据库技术
- Wechat applet obtains the data of ---- onenet and controls the on-board LED of STM32
- activemq--可持久化机制之KahaDB
- 『每日一问』LockSupport怎么实现线程等待、唤醒
- 微信小程序中的列点击隐藏,再点击显示
- &lt;T&gt;泛型方法演示
- excl批量导入数据,后台公共解析方法
- ActiveMQ -- AMQ of persistent mechanism
- jsPDF生成PDF文件,文件不全问题,后台进行文件下载,前台不下载
- [arm] Xintang nuc977 transplants wk2124 drive
猜你喜欢

『每日一问』ReentrantLock加锁解锁

sqli-labs Basic Challenges Less11-22

Ctfhub skill tree Web

Opencv realizes simple face tracking

Programmers can't SQL? Ashes Engineer: all waiting to be eliminated! This is a must skill!
![[C language] dynamic memory management, flexible array](/img/da/b9455885df0cb6646908e3655d62c5.png)
[C language] dynamic memory management, flexible array

uni-app - Refused to display ‘xxx‘ in a frame because an ancestor violates the following Content Sec

Composition of the interview must ask items

Network principle (2) -- network development

Do you know these methods of MySQL database optimization?
随机推荐
Silicon Valley class lesson 11 - official account news and wechat authorization
activemq--可持久化机制之JDBC的journal
ActiveMQ -- leveldb of persistence mechanism
Notes on in-depth analysis of C language 2
Floating point number exploration
28. Slot
Comparison between symmetric encryption and asymmetric encryption
The interviewer asked: how to prevent oversold? There are several ways to achieve it
Mongodb installation and use
@Scheduled源码解析
Redis数据库基础
activemq--可持久化机制之JDBC
log4j2基础配置
Do you know these methods of MySQL database optimization?
『每日一问』怎么实现一个正确的双重检查锁定
黑马程序员JDBC
TCP网络应用程序开发流程
&lt;T&gt;泛型方法演示
sqli-labs Basic Challenges Less11-22
In mysql, update and select are used together