当前位置:网站首页>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
边栏推荐
- Bluebridge cup real topic 2020 palindrome date simulation construction provincial competition
- Oracle SQL table data loss
- Go practice -- generate and read QR codes in golang (skip2 / go QRcode and boombuilder / barcode)
- cookie session jwt
- 大学校园IP网络广播-厂家基于校园局域网的大学校园IP广播方案设计指南
- [practical project] autonomous web server
- Redis 入门和数据类型讲解
- leetcode435. Non overlapping interval
- XML配置文件
- Go practice -- use JWT (JSON web token) in golang
猜你喜欢
(完美解决)matplotlib图例(legend)如何自由设置其位置
appium1.22.x 版本後的 appium inspector 需單獨安裝
JQ style, element operation, effect, filtering method and transformation, event object
XML配置文件
Why is go language particularly popular in China
Oracle SQL table data loss
Go practice -- gorilla / websocket used by gorilla web Toolkit
Webrtc M96 release notes (SDP abolishes Plan B and supports opus red redundant coding)
(subplots用法)matplotlib如何绘制多个子图(轴域)
[basic grammar] Snake game written in C language
随机推荐
[research materials] 2021 annual report on mergers and acquisitions in the property management industry - Download attached
2022-02-11 daily clock in: problem fine brush
Burp suite plug-in based on actual combat uses tips
Compile and decompile GCC common instructions
大学校园IP网络广播-厂家基于校园局域网的大学校园IP广播方案设计指南
小学校园IP网络广播-基于校园局域网的小学IP数字广播系统设计
Go practice -- closures in golang (anonymous functions, closures)
Go language interface learning notes Continued
appium1.22.x 版本後的 appium inspector 需單獨安裝
1099 build a binary search tree (30 points)
1106 lowest price in supply chain (25 points)
Realize file download through the tag of < a > and customize the file name
The process of browser accessing the website
Notes | numpy-07 Slice and index
The principle is simple, but I don't know how to use it? Understand "contemporaneous group model" in one article
【实战项目】自主web服务器
Go practice -- use redis in golang (redis and go redis / redis)
Basic knowledge of reflection (detailed explanation)
Hotel public broadcasting background music - Design of hotel IP network broadcasting system based on Internet +
Introduction to deep learning (II) -- univariate linear regression