当前位置:网站首页>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
边栏推荐
- Redis breakdown penetration avalanche
- 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
- Webapidom get page elements
- Basic knowledge of reflection (detailed explanation)
- Interview question -- output the same characters in two character arrays
- [batch dos-cmd command - summary and summary] - CMD window setting and operation command - close CMD window and exit CMD environment (exit, exit /b, goto: EOF)
- Detailed explanation of the output end (head) of yolov5 | CSDN creation punch in
- Problems encountered in fuzzy query of SQL statements
- [basic grammar] C language uses for loop to print Pentagram
猜你喜欢
![[research materials] 2021 China's game industry brand report - Download attached](/img/b7/a377b0b7c742078e2feb28ebfbca62.jpg)
[research materials] 2021 China's game industry brand report - Download attached

Differences among bio, NiO and AIO

appium1.22. Appium inspector after X version needs to be installed separately

Web APIs exclusivity

Detailed explanation of the output end (head) of yolov5 | CSDN creation punch in

Disassembly and installation of Lenovo r7000 graphics card

XML配置文件
![[Yu Yue education] basic reference materials of interchangeability and measurement technology of Zhongyuan Institute of Technology](/img/f1/d0dc4dc3fe49a2d2cd9e452a0ce31e.jpg)
[Yu Yue education] basic reference materials of interchangeability and measurement technology of Zhongyuan Institute of Technology

Overview of basic knowledge of C language

Use posture of sudo right raising vulnerability in actual combat (cve-2021-3156)
随机推荐
Webrtc protocol introduction -- an article to understand ice, stun, NAT, turn
How to connect the network: Chapter 2 (Part 1): a life cycle of TCP connection | CSDN creation punch in
1095 cars on campus (30 points)
Yolov5 input (I) -- mosaic data enhancement | CSDN creative punch in
[set theory] relation properties (reflexivity | reflexivity theorem | reflexivity | reflexivity theorem | example)
谷歌 | 蛋白序列的深度嵌入和比对
[research materials] 2021 China's game industry brand report - Download attached
Redis 过期淘汰机制
Use posture of sudo right raising vulnerability in actual combat (cve-2021-3156)
Intégration profonde et alignement des séquences de protéines Google
RT thread flow notes I startup, schedule, thread
乾元通多卡聚合路由器的技术解析
Go practice -- closures in golang (anonymous functions, closures)
Introduction to deep learning - definition Introduction (I)
1099 build a binary search tree (30 points)
[research materials] the fourth quarter report of the survey of Chinese small and micro entrepreneurs in 2021 - Download attached
Kept hot standby and haproxy
The process of browser accessing the website
微服务常见面试题
Huawei personally ended up developing 5g RF chips, breaking the monopoly of Japan and the United States