当前位置:网站首页>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;
}
}
边栏推荐
- @TableId can‘t more than one in Class: “com.example.CloseContactSearcher.entity.Activity“.
- Are you ready to automate continuous deployment in ci/cd?
- 48页数字政府智慧政务一网通办解决方案
- 基于SSM框架的文章管理系统
- [2022 the finest in the whole network] how to test the interface test generally? Process and steps of interface test
- 深度学习之环境配置 jupyter notebook
- Business process testing based on functional testing
- JS import excel & Export Excel
- VTK volume rendering program design of 3D scanned volume data
- [daily problem insight] prefix and -- count the number of fertile pyramids in the farm
猜你喜欢
Are you ready to automate continuous deployment in ci/cd?
Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)
深度学习之数据处理
Stm32f407 ------- DAC digital to analog conversion
If the college entrance examination goes well, I'm already graying out at the construction site at the moment
The programmer resigned and was sentenced to 10 months for deleting the code. Jingdong came home and said that it took 30000 to restore the database. Netizen: This is really a revenge
AI super clear repair resurfaces the light in Huang Jiaju's eyes, Lecun boss's "deep learning" course survival report, beautiful paintings only need one line of code, AI's latest paper | showmeai info
Business process testing based on functional testing
陀螺仪的工作原理
【vulnhub】presidential1
随机推荐
Clipboard management tool paste Chinese version
[yolov5 6.0 | 6.1 deploy tensorrt to torch serve] environment construction | model transformation | engine model deployment (detailed packet file writing method)
深度学习之数据处理
Are you ready to automate continuous deployment in ci/cd?
How to judge whether an element in an array contains all attribute values of an object
三维扫描体数据的VTK体绘制程序设计
rancher集成ldap,实现统一账号登录
Random类的那些事
A way of writing SQL, update when matching, or insert
学习光线跟踪一样的自3D表征Ego3RT
stm32F407-------SPI通信
After leaving a foreign company, I know what respect and compliance are
Devops can help reduce technology debt in ten ways
沉浸式投影在线下展示中的三大应用特点
Personal digestion of DDD
509 certificat basé sur Go
【软件逆向-求解flag】内存获取、逆变换操作、线性变换、约束求解
基於GO語言實現的X.509證書
Web project com mysql. cj. jdbc. Driver and com mysql. jdbc. Driver differences
2022/2/11 summary