当前位置:网站首页>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
边栏推荐
- The most understandable life cycle of dependency injection
- 《C语言程序设计》(谭浩强第五版) 第7章 用函数实现模块化程序设计 习题解析与答案
- Iotos IOT middle platform is connected to the access control system of isecure center
- General testing technology [1] classification of testing
- Peut recevoir plusieurs paramètres de type de données - paramètres variables
- ASP. Net 6 middleware series - Custom middleware classes
- Mysql database design specification
- 关于idea调试模式下启动特别慢的优化
- 搭建XAMPP时mysql端口被占用
- C syntax pattern matching [switch expression]
猜你喜欢
Top ten project management software similar to JIRA
Seminar playback video: how to improve Jenkins' ability to become a real Devops platform
Use of slice grammar sugar in C #
“如何实现集中管理、灵活高效的CI/CD”在线研讨会精彩内容分享
. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
IDEA查看历史记录【文件历史和项目历史】
MySQL索引详解【B+Tree索引、哈希索引、全文索引、覆盖索引】
可以接收多種數據類型參數——可變參數
Yes Redis using distributed cache in NE6 webapi
Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800
随机推荐
MySQL索引详解【B+Tree索引、哈希索引、全文索引、覆盖索引】
js递归树结构计算每个节点的叶子节点的数量并且输出
数据库表中不建索引,在插入数据时,通过sql语句防止重复添加(转载)
编码电机PID调试(速度环|位置环|跟随)
C语言实现通讯录----(静态版本)
7-11 rearrange the linked list (25 points)
Course design of Database Principle -- material distribution management system
C syntax sugar empty merge operator [?] And null merge assignment operator [? =]
Xamarin effect Chapter 22 recording effect
Student achievement management
搭建XAMPP时mysql端口被占用
类似Jira的十大项目管理软件
Ningde's position in the times is not guaranteed?
OLED multi-level menu record
JS recursive tree structure calculates the number of leaf nodes of each node and outputs it
[Mysql] LEFT函數 | RIGHT函數
Web Course Design - his system
C introduction of variable parameter params
为什么BI对企业这么重要?
It can receive multiple data type parameters - variable parameters