当前位置:网站首页>Why should we rewrite hashcode when we rewrite the equals method?
Why should we rewrite hashcode when we rewrite the equals method?
2022-07-03 05:16:00 【A wild man about to succeed】
Why do I need to override the equals and hashCode methods in Java?
There are various answers to this question in China , So I went to Stackoverflow I have checked the solution of this problem
Foreign for override the equals and hashCode The explanation of is more contract( contract , Meaning of contract ), in other words , rewrite equals Must be rewritten hashcode Has reached a contract ( Or rather, Theorem ?)
This article comes from the analysis of this comment
Why do I need to override the equals and hashCode methods in Java?

The author answers like this :
image HashMap and HashSet Is through the object hashcode To store objects , And when locating objects, you can also use hashcode
Hash retrieval is a two-step process .
Find the right bucket ( Use hashCode())
Search the bucket for the correct element ( Use equals())
Here is a small example , Explain why we rewrite equals() And need to rewrite hashcode()
Build a Employee class , It has two variables age and name
public class Employee {
String name;
int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Employee))
return false;
Employee employee = (Employee) obj;
return employee.getAge() == this.getAge()
&& employee.getName() == this.getName();
}
// Commented out
/* @Override
public int hashCode() {
int result=17;
result=31*result+age;
result=31*result+(name!=null ? name.hashCode():0);
return result;
}
*/
}Create a test class ClientTest
public class ClientTest {
public static void main(String[] args) {
Employee employee = new Employee("rajeev", 24);
Employee employee1 = new Employee("rajeev", 25);
Employee employee2 = new Employee("rajeev", 24);
HashSet<Employee> employees = new HashSet<Employee>();
employees.add(employee);
System.out.println(employees.contains(employee2));
System.out.println("employee.hashCode(): " + employee.hashCode()
+ " employee2.hashCode():" + employee2.hashCode());
}
}There are notes When , He'll print it out
false employee.hashCode(): 321755204 employee2.hashCode(): 375890482
Now we uncomment hashcode(), He'll print it out
true employee.hashCode(): -938387308 employee2.hashCode(): -938387308
In the first case , Two objects As like as two peas , however hashcode Dissimilarity ( Even if equals() Method is overridden ,hashcode It's still different )
But we Think employee and employee2 yes equally Of ( If we add 100 m name="rajeev",age=24 The object of , that Hashset There will be 100 Ten thousand such " identical " The object of , That's clearly not what we want )
If the traditional hashcode() Method cannot reflect this , Then we need rewrite hashcode() Method . Make two objects equal , Their hash codes are also equal
边栏推荐
- Yolov5 input (I) -- mosaic data enhancement | CSDN creative punch in
- [research materials] 2021 China's game industry brand report - Download attached
- study hard and make progress every day
- Redis 入门和数据类型讲解
- Congratulations to musk and NADELLA on their election as academicians of the American Academy of engineering, and Zhang Hongjiang and Fang daining on their election as foreign academicians
- 穀歌 | 蛋白序列的深度嵌入和比對
- 1087 all roads lead to Rome (30 points)
- Oracle SQL table data loss
- Go practice -- gorilla / websocket used by gorilla web Toolkit
- 在PyCharm中配置使用Anaconda环境
猜你喜欢
![[set theory] relationship properties (common relationship properties | relationship properties examples | relationship operation properties)](/img/af/8dfa783c87363a9d75c52e7680d508.jpg)
[set theory] relationship properties (common relationship properties | relationship properties examples | relationship operation properties)

Congratulations to musk and NADELLA on their election as academicians of the American Academy of engineering, and Zhang Hongjiang and Fang daining on their election as foreign academicians

5-36v input automatic voltage rise and fall PD fast charging scheme drawing 30W low-cost chip

Audio Focus Series: write a demo to understand audio focus and audiomananger

"Hands on deep learning" pytorch edition Chapter II exercise

大学校园IP网络广播-厂家基于校园局域网的大学校园IP广播方案设计指南
![[research materials] 2022q1 game preferred casual game distribution circular - Download attached](/img/13/5a67c5d08131745759fdc70a71cf0f.jpg)
[research materials] 2022q1 game preferred casual game distribution circular - Download attached

RT thread flow notes I startup, schedule, thread

Detailed explanation of yolov5 training own data set
![[basic grammar] Snake game written in C language](/img/cb/83631ef3ccd7047ca42d33dc49bf90.jpg)
[basic grammar] Snake game written in C language
随机推荐
Botu uses peek and poke for IO mapping
谷歌 | 蛋白序列的深度嵌入和比对
1103 integer factorization (30 points)
Handler understands the record
Principles of BTC cryptography
Make your own dataset
【批处理DOS-CMD命令-汇总和小结】-CMD窗口的设置与操作命令-关闭cmd窗口、退出cmd环境(exit、exit /b、goto :eof)
The consumption of Internet of things users is only 76 cents, and the price has become the biggest obstacle to the promotion of 5g industrial interconnection
BTC-密码学原理
Go practice -- generate and read QR codes in golang (skip2 / go QRcode and boombuilder / barcode)
Detailed explanation of the output end (head) of yolov5 | CSDN creation punch in
Interview question -- output the same characters in two character arrays
Yolov5 network structure + code + application details | CSDN creation punch in
[clock 223] [binary tree] [leetcode high frequency]: 102 Sequence traversal of binary tree
JQ style, element operation, effect, filtering method and transformation, event object
1115 counting nodes in a BST (30 points)
(subplots usage) Matplotlib how to draw multiple subgraphs (axis field)
[practical project] autonomous web server
[develop wechat applet local storage with uni app]
5-36v input automatic voltage rise and fall PD fast charging scheme drawing 30W low-cost chip