当前位置:网站首页>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 !)

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
     Insert picture description here
  • 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 . Insert picture description here
  • In the custom class equals() And hashCode() Method ( Not rewritten )
     Insert picture description here
  • String Internally rewritten equals Method
     Insert picture description here

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 :

  1. Judge whether the address of this object is the same as that of the transmitted object
  2. Use instanceof Judgment type
  3. 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

  1. 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 .
  2. 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 :
 Insert picture description here

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;
	}
}

原网站

版权声明
本文为[A very lazy person]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061653480062.html