当前位置:网站首页>9. Talk about the relationship between hashcode() and equals()?
9. Talk about the relationship between hashcode() and equals()?
2022-07-18 16:05:00 【Jasonakeke】
say something hashCode and equals The relationship between ?
Last article about introduction Object Several methods under this category are interview questions , mention equals() and hashCode() Methods may lead to questions about “hashCode() and equals() The relationship between ?” The interview questions , This article analyzes this basic interview question .
Sacrifice a picture first , Think about why ?

Introduce
equals() Is used to determine whether two objects are equal .
hashCode() To get hash code , Also known as hash code ; It actually returns a int Integers . The function of this hash code is to determine the index position of the object in the hash table .
Relationship
We use “ Class ” to “hashCode() and equals() The relationship between ” branch 2 To illustrate .
Does not create “ Class ”
What I'm talking about here “ The hash table corresponding to the class will not be created ” Is said : We will not be in HashSet, Hashtable, HashMap And so on these are essentially hash table data structures , Use this class . for example , This class will not be created HashSet aggregate .
under these circumstances , Of the class “hashCode() and equals() ” It's nothing to do with half a cent !equals() Used to compare whether two objects of this class are equal . and hashCode() It doesn't work at all .
below , Let's look at the example to see that two objects of a class are equal as well as Wait a moment hashCode() The value of .
import java.util.*;
import java.lang.Comparable;
/** * @desc Compare equals() return true as well as return false when , hashCode() Value . * */
public class NormalHashCodeTest{
public static void main(String[] args) {
// newly build 2 The same thing Person object ,
// Reuse equals Compare them for equality
Person p1 = new Person("eee", 100);
Person p2 = new Person("eee", 100);
Person p3 = new Person("aaa", 200);
System.out.printf("p1.equals(p2) : %s; p1(%d) p2(%d)\n", p1.equals(p2), p1.hashCode(), p2.hashCode());
System.out.printf("p1.equals(p3) : %s; p1(%d) p3(%d)\n", p1.equals(p3), p1.hashCode(), p3.hashCode());
}
/** * @desc Person class . */
private static class Person {
int age;
String name;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " - " +age;
}
/** * @desc Cover equals Method */
public boolean equals(Object obj){
if(obj == null){
return false;
}
// If the same object returns true, Instead, return to false
if(this == obj){
return true;
}
// Judge whether the type is the same
if(this.getClass() != obj.getClass()){
return false;
}
Person person = (Person)obj;
return name.equals(person.name) && age==person.age;
}
}
}
Running results :
p1.equals(p2) : true; p1(1169863946) p2(1901116749)
p1.equals(p3) : false; p1(1169863946) p3(2131949076)
It can be seen from the results :p1 and p2 In the case of equality ,hashCode() It doesn't have to be the same .
Will create “ Class ”
What I'm talking about here “ The hash table corresponding to the class will be created ” Is said : We will be in HashSet, Hashtable, HashMap And so on these are essentially hash table data structures , Use this class . for example , This class will be created HashSet aggregate .
under these circumstances , Of the class “hashCode() and equals() ” It matters :
If two objects are equal , So their hashCode() The value must be the same . Equality here means , adopt equals() Returns... When comparing two objects true.
If two objects hashCode() equal , They are not necessarily equal . Because it's in the hash table ,hashCode() equal , That is, the hash values of two key value pairs are equal . But the hash is the same , It's not necessarily the case that the key-value pairs are equal . Add that :“ Two different key value pairs , Hash values are equal ”, This is hash conflict .
Besides , under these circumstances . To determine whether two objects are equal , Except to cover equals() outside , Also cover hashCode() function . otherwise ,equals() Invalid .
give an example , establish Person Class HashSet aggregate , Must cover... At the same time Person Class equals() and hashCode() Method .
If it's just covering equals() Method . We will find that ,equals() The method didn't achieve the effect we wanted .
import java.util.*;
import java.lang.Comparable;
/** * @desc Compare equals() return true as well as return false when , hashCode() Value . * */
public class ConflictHashCodeTest1{
public static void main(String[] args) {
// newly build Person object ,
Person p1 = new Person("eee", 100);
Person p2 = new Person("eee", 100);
Person p3 = new Person("aaa", 200);
// newly build HashSet object
HashSet set = new HashSet();
set.add(p1);
set.add(p2);
set.add(p3);
// Compare p1 and p2, And print their hashCode()
System.out.printf("p1.equals(p2) : %s; p1(%d) p2(%d)\n", p1.equals(p2), p1.hashCode(), p2.hashCode());
// Print set
System.out.printf("set:%s\n", set);
}
/** * @desc Person class . */
private static class Person {
int age;
String name;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "("+name + ", " +age+")";
}
/** * @desc Cover equals Method */
@Override
public boolean equals(Object obj){
if(obj == null){
return false;
}
// If the same object returns true, Instead, return to false
if(this == obj){
return true;
}
// Judge whether the type is the same
if(this.getClass() != obj.getClass()){
return false;
}
Person person = (Person)obj;
return name.equals(person.name) && age==person.age;
}
}
}
Running results :
p1.equals(p2) : true; p1(1169863946) p2(1690552137)
set:[(eee, 100), (eee, 100), (aaa, 200)]
Result analysis :
We rewrote Person Of equals(). however , It's a strange discovery :HashSet There are still repeating elements in :p1 and p2. Why does this happen ?
This is because although p1 and p2 The content of is equal , But their hashCode() Unequal ; therefore ,HashSet Adding p1 and p2 When , Think they are not equal .
That covers at the same time equals() and hashCode() Methods? ?
import java.util.*;
import java.lang.Comparable;
/** * @desc Compare equals() return true as well as return false when , hashCode() Value . * */
public class ConflictHashCodeTest2{
public static void main(String[] args) {
// newly build Person object ,
Person p1 = new Person("eee", 100);
Person p2 = new Person("eee", 100);
Person p3 = new Person("aaa", 200);
Person p4 = new Person("EEE", 100);
// newly build HashSet object
HashSet set = new HashSet();
set.add(p1);
set.add(p2);
set.add(p3);
// Compare p1 and p2, And print their hashCode()
System.out.printf("p1.equals(p2) : %s; p1(%d) p2(%d)\n", p1.equals(p2), p1.hashCode(), p2.hashCode());
// Compare p1 and p4, And print their hashCode()
System.out.printf("p1.equals(p4) : %s; p1(%d) p4(%d)\n", p1.equals(p4), p1.hashCode(), p4.hashCode());
// Print set
System.out.printf("set:%s\n", set);
}
/** * @desc Person class . */
private static class Person {
int age;
String name;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " - " +age;
}
/** * @desc rewrite hashCode */
@Override
public int hashCode(){
int nameHash = name.toUpperCase().hashCode();
return nameHash ^ age;
}
/** * @desc Cover equals Method */
@Override
public boolean equals(Object obj){
if(obj == null){
return false;
}
// If the same object returns true, Instead, return to false
if(this == obj){
return true;
}
// Judge whether the type is the same
if(this.getClass() != obj.getClass()){
return false;
}
Person person = (Person)obj;
return name.equals(person.name) && age==person.age;
}
}
}
Running results :
p1.equals(p2) : true; p1(68545) p2(68545)
p1.equals(p4) : false; p1(68545) p4(68545)
set:[aaa - 200, eee - 100]
Result analysis :
this time ,equals() It works ,HashSet There is no repeating element .
Compare p1 and p2, We found that : Their hashCode() equal , adopt equals() Comparing them also returns true. therefore ,p1 and p2 Regarded as equal .
Compare p1 and p4, We found that : Although they are hashCode() equal ; however , adopt equals() Compare them back to false. therefore ,p1 and p4 Regarded as unequal .
principle
Same object ( No modification has occurred ) Whenever called hashCode() The returned value must be the same .
If one key The object is put Called when hashCode() Determines the storage location , And in the get Called when hashCode() Got a different return value , This value maps to a different place , Then you can't find the original key value .hashCode() Objects whose return values are equal are not necessarily equal , adopt hashCode() and equals() Must be able to uniquely identify an object . Of unequal objects hashCode() The results can be equal .hashCode() When paying attention to the collision problem , We should also pay attention to the generation speed , perfect hash Not reality .
Once rewritten equals() function ( rewrite equals We should also pay attention to meet the reflexivity 、 symmetry 、 Transitivity 、 Uniformity ), It has to be rewritten hashCode() function . and hashCode() The basis for generating hash value of should be equals() The field used to compare equality in .
If two by equals() Specifies that equal objects are generated hashCode Unequal , about hashMap Come on , They are likely to map to different locations , There is no call equals() Compare equal opportunities , Two objects that are actually equal may be inserted in different positions , There is an error . Other collection classes based on Hash methods may also have this problem
边栏推荐
- ELK集群部署(二)之部署kibana
- Web page making (II)
- Renewable finance refi: providing technology and financial system beneficial to the earth
- LCA problem topic
- JS calculation accuracy and data format
- 中关村e谷·苏高新承办2022苏州中日韩高层次人才项目路演大赛
- 9. 说说hashCode() 和 equals() 之间的关系?
- VR (I) ATW ASW
- ARTS_ 202207W1
- 数据库系统原理与应用教程(021)—— MySQL 的数据库操作
猜你喜欢
随机推荐
ELK集群部署(四)之部署Logstash
Assist developers to comprehensively interpret APIs IX test cases
"Detective Conan" 1049 words painting collapse, the role of frequent "face changes"
[training Day2] cinema ticket [combinatorics] [Cartland number]
cpu由什么组成
ReFi夏季升温:Uniswap v3和绿色资产池在Celo上启动
Graphic array calculation module numpy (trigonometric function, rounding function, converting radian to angle, statistical analysis function, median, array sorting, argsort(), lexport())
Autojs learning - Application List
Learn about Max again_ allowed_ packet
Power buckle ----- gemstones and stones
面试秘籍大放送,编测编学独家秘籍遭外泄?!
1388. 3n 块披萨 动态规划
从IT研发人员离职工作交接想到的
全面解析NFT的流动性问题与解决方案
ELK集群部署(七)之ELK集群启动顺序
Solution to slow running card of VMware virtual machine
启用远程 rsyslog 日志服务
中关村e谷·苏高新承办2022苏州中日韩高层次人才项目路演大赛
Big guy said * computing talk Club | Sanxingdui fantasy trip: an experience that only cloud computing can bring
玩转“私域电商”,链动2+1模式值得企业深入了解吗?







![[vsCTF2022]web题目复现](/img/6f/56a9ec14ec699e427e9e21ee48c9eb.png)

