当前位置:网站首页>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;
}
}
边栏推荐
- C language input / output stream and file operation [II]
- Are you ready to automate continuous deployment in ci/cd?
- 准备好在CI/CD中自动化持续部署了吗?
- Mujoco Jacobi - inverse motion - sensor
- 代码克隆的优缺点
- How engineers treat open source -- the heartfelt words of an old engineer
- Matlab learning notes
- Markov decision process
- Mujoco second order simple pendulum modeling and control
- Advanced learning of MySQL -- basics -- transactions
猜你喜欢
Imeta | Chen Chengjie / Xia Rui of South China Agricultural University released a simple method of constructing Circos map by tbtools
uniapp实现从本地上传头像并显示,同时将头像转化为base64格式存储在mysql数据库中
沉浸式投影在线下展示中的三大应用特点
Racher integrates LDAP to realize unified account login
2022/2/11 summary
File and image comparison tool kaleidoscope latest download
Data analysis course notes (III) array shape and calculation, numpy storage / reading data, indexing, slicing and splicing
St table
【vulnhub】presidential1
[2022 the finest in the whole network] how to test the interface test generally? Process and steps of interface test
随机推荐
如何判断一个数组中的元素包含一个对象的所有属性值
threejs图片变形放大全屏动画js特效
rancher集成ldap,实现统一账号登录
Explain in detail the implementation of call, apply and bind in JS (source code implementation)
Leecode brush question record sword finger offer 58 - ii Rotate string left
Leecode brush questions record sword finger offer 44 A digit in a sequence of numbers
2021 SASE integration strategic roadmap (I)
Memory optimization of Amazon memorydb for redis and Amazon elasticache for redis
一图看懂对程序员的误解:西方程序员眼中的中国程序员
Advanced learning of MySQL -- Fundamentals -- four characteristics of transactions
Model-Free Prediction
How to use vector_ How to use vector pointer
Leecode brush question record sword finger offer 56 - ii Number of occurrences of numbers in the array II
[2022 the finest in the whole network] how to test the interface test generally? Process and steps of interface test
Quaternion attitude calculation of madgwick
St table
三维扫描体数据的VTK体绘制程序设计
Command line kills window process
@TableId can‘t more than one in Class: “com.example.CloseContactSearcher.entity.Activity“.
英雄联盟|王者|穿越火线 bgm AI配乐大赛分享