当前位置:网站首页>Equals() and hashcode()
Equals() and hashcode()
2022-07-07 00:42:00 【A very lazy person】
This paper mainly introduces hashCode() And equals() Principle , And it describes the method body of rewriting the two , And its use in collections ( Ensure that the contents of objects in the collection are not repeated !)
List of articles
Preface
stay java There is a common parent class in Object , All objects implicitly inherit this class , among equals() And hashCode() Is the inherited method .
equals() By default, when comparing two objects , Compare its address ( Because all classes inherit Object,Object Its internal use is == Compare ,== Used to judge whether the memory addresses on both sides are the same )
eg:person01.equals(person02) It is to judge whether the addresses of two objects in the memory heap are the same . Because it is a method that inherits the parent class , We can naturally rewrite this method when writing programs , We know String It has been rewritten internally equals Method ( Self defined classes are not overridden by default ), As shown below !hashCode() And equals() be similar , But it uses native The method of decoration ( There will be an explanation ), It returns an integer by default (jvm There are some contracts by default , All manufacturers will abide by this contract by default , There will be an explanation ), But custom classes inherit by default Object, Naturally, it can also be rewritten hashCode() Method ( stay TreeSet This method is used for storing objects in , There will be a detailed explanation below !)
Object in equals() And hashCode() Method
- One native The way is a Java Call not Java Code interface . One native Method means that the implementation of the method is not Java Language implementation , For example, use C or C++ Realization .
In the custom class equals() And hashCode() Method ( Not rewritten )
String Internally rewritten equals Method
1.equals()
(1)equals() brief introduction
equals() When not rewritten , Default inheritance Object Methods , stay Object Of equals() Use == Judge ,== It determines whether the addresses of two objects are the same ,String Is an exception, which is rewritten internally equals Method , So you can use equals() Method to determine whether the contents of the string are equal , It can be overridden in our custom class equals Method , Realize the judgment of user-defined object content !
(2)equals() rewrite ( To judge whether the contents of custom class objects are equal )
step :
- Judge whether the address of this object is the same as that of the transmitted object
- Use instanceof Judgment type
- According to the type result ( May be , Maybe not ), Do type conversion , Compare the attribute values
The code example is as follows :
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
// Judge whether the address of this object is the same as that of the transmitted object
if (this==obj) {
return true;
// Judge obj Whether to belong to Person class
}else if (obj instanceof Person) {
// If it is , Parent rotor class
Person p=(Person)obj;
// Determine whether each attribute is the same
if (p.name.equals(this.name)&&p.age==this.age) {
return true;
}
}
// Different return false
return false;
}
2.hashCode() And memory address
Conclusion : hashCode What is returned is not necessarily the object's ( fictitious ) Memory address , It may be related to the memory address , Depending on the runtime library and JVM The concrete realization of .
(1)native
native Mainly used for methods
- One native The way is a Java Call not Java Code interface . One native Method means that the implementation of the method is not Java Language implementation , For example, use C or C++ Realization .
- Defining a native When the method is used , Does not provide an implementer ( It's more like defining a Java Interface), Because its realization is caused by non Java Language is realized on the outside
- Be careful :
Mainly because JAVA Unable to operate on the underlying operating system , But it can go through jni(java native interface) Call other languages to achieve the underlying access .
(2)Object.hashCode()
Reference resources :Java Of Object.hashCode() Is the return value of the object memory address ?
Object.hashCode It's a native Method , I can't see the source code (Java Code ,Oracle Of JDK It's invisible ,OpenJDK Or other open source JRE We can find the corresponding C/C++ Code ).
Object.hashCode() stay JRE(Java Runtime Library) Some contracts that should be followed in (contract):(PS: The so-called contract is, of course, reached by consensus , each JVM Manufacturers will follow )
- Uniformity (consistent), In one execution of a program , The same integer must be returned consistently for the same object .
- If two objects pass through equals(Object) Compare , The result is equal , Then call the two objects respectively hashCode Method should produce the same integer result .(PS: here equals and hashCode It's all about Object Class )
- If two objects pass through java.lang.Object.equals(java.lang.Ojbect) Compare , The results are not equal , It is not necessary to guarantee that these two objects are called separately hashCode Also returns two different integers .
(3) special hashCode
- String: As long as the string content is the same ,hashCode Also the same .
- Integer: Back to hashCode Is the value of an integer contained in its object .
(4) rewrite Object.hashCode()
@Override
public int hashCode() {
// TODO Auto-generated method stub
// Returns the property of hashCode, Don't use jvm The default contract returns hashCode value
// As long as the values of strings are equal , Its hashCode The value is equal
int numName=this.name.hashCode();
return numName+this.age;
}
3.hashCode() And equals() Use in collections
- If two objects equals() by true, that hashCode It must be the same , The reverse is not true , That is, if two objects hashCode identical , It cannot be concluded that these two objects are equal .
- If you use objects as Map Of key, Or in the Set When storing data in a collection (
To ensure the uniqueness of the value
), Then rewrite it at the same time hashCode and equals() Talent , And ensure the consistency of the two .reason :
( stay Set When you add data to a collection , It will first judge the call between the newly added data and the original data in the set hashCode() Methods to judge hashCode Whether the values are equal , If they are not equal, add new elements directly to the set , If equal, call equals() Method to determine whether the result is true, if true Do not add ,false Then add )
- Code example :
test result :
Test.java
public class Test {
public static void main(String[] args) {
Person person01=new Person(" Zhang San ", 18);
Person person02=new Person(" Zhang San ", 18);
Person person03=new Person(" Li Si ", 18);
HashSet<Person> hashSet=new HashSet<Person>();
hashSet.add(person01);
hashSet.add(person02);
hashSet.add(person03);
Iterator<Person> iterator=hashSet.iterator();
while(iterator.hasNext()) {
Person person=iterator.next();
System.out.println(person);
}
}
}
Person.java
package day15.demo01;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
// Judge whether the address of this object is the same as that of the transmitted object
if (this==obj) {
return true;
// Judge obj Whether to belong to Person class
}else if (obj instanceof Person) {
// If it is , Parent rotor class
Person p=(Person)obj;
// Determine whether each attribute is the same
if (p.name.equals(this.name)&&p.age==this.age) {
return true;
}
}
// Different return false
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
// Returns the property of hashCode, Don't use jvm The default contract returns hashCode value
// As long as the values of strings are equal , Its hashCode The value is equal
int numName=this.name.hashCode();
return numName+this.age;
}
}
边栏推荐
- Advanced learning of MySQL -- basics -- multi table query -- inner join
- 2022/2/10 summary
- Typescript incremental compilation
- Command line kills window process
- [2022 the finest in the whole network] how to test the interface test generally? Process and steps of interface test
- What is web penetration testing_ Infiltration practice
- 陀螺仪的工作原理
- 【vulnhub】presidential1
- How engineers treat open source -- the heartfelt words of an old engineer
- uniapp中redirectTo和navigateTo的区别
猜你喜欢
从外企离开,我才知道什么叫尊重跟合规…
Geo data mining (III) enrichment analysis of go and KEGG using David database
JS+SVG爱心扩散动画js特效
学习使用代码生成美观的接口文档!!!
基於GO語言實現的X.509證書
iMeta | 华南农大陈程杰/夏瑞等发布TBtools构造Circos图的简单方法
alexnet实验偶遇:loss nan, train acc 0.100, test acc 0.100情况
JWT signature does not match locally computed signature. JWT validity cannot be asserted and should
2022/2/11 summary
Mujoco finite state machine and trajectory tracking
随机推荐
Alexnet experiment encounters: loss Nan, train ACC 0.100, test ACC 0.100
ZYNQ移植uCOSIII
Geo data mining (III) enrichment analysis of go and KEGG using David database
Advanced learning of MySQL -- Fundamentals -- concurrency of transactions
2021 SASE integration strategic roadmap (I)
Encryption algorithm - password security
Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)
equals()与hashCode()
AI超清修复出黄家驹眼里的光、LeCun大佬《深度学习》课程生还报告、绝美画作只需一行代码、AI最新论文 | ShowMeAI资讯日报 #07.06
2022/2/10 summary
threejs图片变形放大全屏动画js特效
2022/2/12 summary
Policy Gradient Methods
37 page overall planning and construction plan for digital Village revitalization of smart agriculture
Leecode brushes questions to record interview questions 17.16 massagist
Leecode brush questions record interview questions 32 - I. print binary tree from top to bottom
What can the interactive slide screen demonstration bring to the enterprise exhibition hall
How to set encoding in idea
How engineers treat open source -- the heartfelt words of an old engineer
If the college entrance examination goes well, I'm already graying out at the construction site at the moment