当前位置:网站首页>Do you really understand hashcode and equals???
Do you really understand hashcode and equals???
2022-04-23 03:16:00 【Xiaodaoxian 97】
Preface
Today I'm still talking about , Maybe my resume will be no different from that just graduated in three years , Because it has been almost a year since graduation , The last time I rewritten my resume, there was no difference except that I had two more project experience , And I still need a long time to master the skills on my resume .
One 、 About hashCode and equals We know the following points
- hashCode Two objects that are the same are not necessarily the same
- equals The same two objects ,hashCode It must be the same
- rewrite equals It must be rewritten hashCode
The rest of the
- == Compare the memory address values of the two objects
- equals The comparison is whether the values in the two objects are the same , Not rewritten equals and == equally
Two 、hashCode The origin of
We know hashCode yes Object Methods , But when we click in, we can see that it is a native Method , That is, it's not up to us Java To achieve , The bottom is C Written , We understand the default hashCode It is generated based on memory address
public native int hashCode();
3、 ... and 、 How to rewrite hashCode
rewrite hashCode The basic rules are as follows :
- While the program is running , The same object is called more than once hashCode() Method should return the same value .
- When two objects pass through equals() Method comparison return true when , Then two objects of hashCode() Method returns an equal value .
- Object is used as equals() The method is standard Field, Should be used to calculate hashCode value .
According to each of our attributes hashCode, Then add certain rules to calculate the new hashCode
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getFromUserId() == null) ? 0 : getFromUserId().hashCode());
result = prime * result + ((getFromUserName() == null) ? 0 : getFromUserName().hashCode());
result = prime * result + ((getToUserId() == null) ? 0 : getToUserId().hashCode());
result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode());
result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
result = prime * result + ((getUnReadFlag() == null) ? 0 : getUnReadFlag().hashCode());
return result;
}
Four 、 How to rewrite equals
- Directly determine the address value of two objects ( use ==)
- Judge whether the object to be compared is null
- Determine whether two objects are a class ( Compare getClass)
- Call the of each property of the object equals Compare , Considering that the properties of the object may be null, So we have to judge whether it is null
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
MsgInfo other = (MsgInfo) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getFromUserId() == null ? other.getFromUserId() == null : this.getFromUserId().equals(other.getFromUserId()))
&& (this.getFromUserName() == null ? other.getFromUserName() == null : this.getFromUserName().equals(other.getFromUserName()))
&& (this.getToUserId() == null ? other.getToUserId() == null : this.getToUserId().equals(other.getToUserId()))
&& (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
&& (this.getUnReadFlag() == null ? other.getUnReadFlag() == null : this.getUnReadFlag().equals(other.getUnReadFlag()));
}
notes : above hashCode and equals All are IDEA Automatically generated
5、 ... and 、 When to rewrite equals and hashCode
We all know that when we use HashMap Such a special container requires , But why exactly ?
There is an interview question like this :
Q: Why? String Such a packing data type is more suitable for hashMap Of key
A: because String Such wrapper data types are rewritten hashCode and equals
In fact, we basically use String As hashMap Of key, Consider if we use custom classes as key What will happen ?
import java.util.HashMap;
import java.util.Map;
public class Test {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static Map<Test,Object> map = new HashMap<>();
static {
Test test = new Test();
test.setName(" Xiaodaoxian ");
test.setAge(18);
map.put(test," WOW! ");
}
}
Think about how you can get this map The only data in it ?( Remove convenience , You can use map.get() Methods? ?)
public static void main(String[] args) {
Test test = new Test();
test.setName(" Xiaodaoxian ");
test.setAge(18);
System.out.println(map.get(test));
}
What is printed in the above way is null, We didn't rewrite hashCode and equals Before , We rewrite new And the objects previously set in them hashCode and equals Never the same .
So when we use custom objects as hashKey Be sure to rewrite when you hashCode and equals.
6、 ... and 、 Why rewrite equals It must be rewritten hashCode
Because of hashMap And similar containers , Each search needs to be compared , If used directly equals Certainly. , But the price is too high , So the strategy is to compare hashCode,hashCode Compare the same equals.
Instead of rewriting hashCode, The default generation is related to the memory address , Never the same .
版权声明
本文为[Xiaodaoxian 97]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230315096762.html
边栏推荐
- Is it difficult to choose binary version control tools? After reading this article, you will find the answer
- 2022g2 boiler stoker examination question bank and online simulation examination
- yes. Net future
- Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
- MySql分组查询规则
- Preview of converting doc and PDF to SWF file
- 7-11 rearrange the linked list (25 points)
- Configuration table and page information automatically generate curd operation page
- The backtracking of stack is used to solve the problem of "the longest absolute path of file"
- Xamarin effect Chapter 21 expandable floating operation button in GIS
猜你喜欢

“如何实现集中管理、灵活高效的CI/CD”在线研讨会精彩内容分享

2022年度Top9的任务管理系统

2022t elevator repair test simulation 100 questions and online simulation test

MySql关键字GROUP_CONCAT,组合连接查询

2022a special equipment related management (elevator) work license question bank and simulation examination

OLED多级菜单记录

Seminar playback video: how to improve Jenkins' ability to become a real Devops platform

Xamarin effect Chapter 21 expandable floating operation button in GIS

类似Jira的十大项目管理软件
![[new version release] componentone added Net 6 and blazor platform control support](/img/08/71e7328f685a5cdd584f1bfdce5f2a.png)
[new version release] componentone added Net 6 and blazor platform control support
随机推荐
ThreadLocal 测试多线程变量实例
Use of slice grammar sugar in C #
The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
Configure automatic implementation of curd projects
C read / write binary file
月薪10k-20k都无法回答的事务问题,你会吗?
Peut recevoir plusieurs paramètres de type de données - paramètres variables
Ningde's position in the times is not guaranteed?
[MySQL] left Function | Right Function
Chapter 8 of C language programming (fifth edition of Tan Haoqiang) is good at using pointer exercises to analyze and answer
After the mobile phone is connected to the computer, how can QT's QDIR read the mobile phone file path
The most easy to understand dependency injection and control inversion
通过 zxing 生成二维码
Charles uses three ways to modify requests and responses
PID debugging of coding motor (speed loop | position loop | follow)
《C语言程序设计》(谭浩强第五版) 第8章 善于利用指针 习题解析与答案
2022年P气瓶充装培训试题及模拟考试
Fight leetcode again (290. Word law)
2022G2电站锅炉司炉考试题库及在线模拟考试
编码电机PID调试(速度环|位置环|跟随)