Preface
In Java,equals()
Methods are important methods for comparing whether two objects are equal. It belongs toObject
class method, so all Java objects inherit this method. but,Object
In the classequals()
The default implementation of the method is to compare whether the references of two objects are the same, that is, whether they point to the same object in memory. In actual development, we often need to judge whether it is equal based on the actual content of the object, and then we need to rewrite it.equals()
method.
1. Understanding of the equals() method
equals()
Methods are used to compare whether the contents of two objects are equal, rather than whether their references are the same. For example, we have twoPerson
Objects, their names and ages are the same, but they are two separate objects stored in different locations in memory. If we want to determine whether these two objects are "equal" (i.e., their properties are the same), we need to rewrite itequals()
method.
2. Use of equals() method
1. Rewrite the equals() method
When we need to compare the contents of two objects, we need to rewrite itequals()
method. When rewriting, the following principles need to be followed:
- Reflexivity: For any non-null reference value x,
(x)
Must returntrue
。 - Symmetry: For any non-null reference values x and y, if and only if
(x)
returntrue
hour,(y)
Must returntrue
。 - Transitive: For any non-null reference values x, y, and z, if
(y)
returntrue
,and(z)
returntrue
,So(z)
Should returntrue
。 - Consistency: multiple calls for any non-null reference values x and y
(y)
Always returntrue
Or always returnfalse
, the premise is on the objectequals
The information used in the comparison has not been modified. - For any non-null reference value x,
(null)
Must returnfalse
。
Sample code:
public class Person { private String name; private int age; // Constructor, getter and setter methods are omitted... @Override public boolean equals(Object obj) { // 1. Check whether it is referenced to the same object if (this == obj) { return true; } // 2. Check whether the incoming object is null and whether the type matches if (obj == null || getClass() != ()) { return false; } // 3. Type matching, transform obj into Person type Person other = (Person) obj; // 4. Compare whether the attributes are equal return age == && (name == null ? == null : ()); } @Override public int hashCode() { // When overriding the equals method, it is usually necessary to override the hashCode method to maintain the general convention of hashCode // Use simple calculation methods here, and more complex calculations may be required in practical applications to ensure uniform hash distribution return (name, age); } }
2. Use the equals() method
Rewriteequals()
After the method, we can use it to compare whether the contents of the two objects are equal.
Sample code:
public class Main { public static void main(String[] args) { Person person1 = new Person("Alice", 25); Person person2 = new Person("Alice", 25); Person person3 = new Person("Bob", 30); // Use the equals() method to compare whether the object content is equal or not ("person1 equals person2: " + (person2)); // Output: true ("person1 equals person3: " + (person3)); // Output: false // Note: Do not use == to compare whether the object content is equal ("person1 == person2: " + (person1 == person2)); // Output: false, because person1 and person2 are two different objects } }
In the example above, we created threePerson
object, and useequals()
Methods compare whether their contents are equal. You can see, evenperson1
andperson2
are two different objects, but because their properties are the same,(person2)
returntrue
. andperson1
andperson3
The properties of(person3)
returnfalse
。
Summarize
equals()
Methods play a very important role in Java, especially when dealing with object comparisons. By default,equals()
Method inherits fromObject
Class, just compares whether the references of two objects are the same, that is, whether they point to the same location in memory. However, in practical applications, we often need to judge whether they are equal based on the actual content of the object (i.e. the properties of the object). At this time, it needs to be rewritedequals()
method.
Rewriteequals()
When doing the method, the rules of reflexivity, symmetry, transitiveness, consistency and comparison between non-null objects and null are required. When comparing object properties, if the properties are also objects, then the objects should be called recursivelyequals()
Methods are compared, rather than simply using==
Operator.
Also, when rewriteequals()
When it comes to methods, it usually needs to be rewritedhashCode()
method to ensure that two equal objects have the same hash code. This is because in Java, many collection classes (such asHashSet
、HashMap
etc.) all depend onhashCode()
Methods to achieve efficient element storage and retrieval.
useequals()
When doing the method, be careful not to==
Operator confusion.==
The operator is used to compare whether the references of two objects are the same, andequals()
Methods are used to compare whether the contents of two objects are equal.
In short, understand and use correctlyequals()
Methods are an indispensable part of Java programming. By rewriteequals()
Method, we can judge whether they are equal based on the actual content of the object, thereby more accurately processing the logic of object comparison. At the same time, you should also pay attention to==
The difference between operators to avoid logical errors in the code.
Attachment: Exercises for rewriting equals methods
package object; /* Determine whether the contents of two person objects are equal If the attribute values of the two person objects are the same, then true is returned, otherwise false is returned */ public class EqualsExercise { public static void main(String[] args) { Person person1 = new Person("jack", 10, 'male'); Person person2 = new Person("jack", 10, 'male'); ((person2)); //The output result is true } } class Person { private String name; private int age; private char gender; //Rewrite the equals method of Object public boolean equals(Object obj) { //If the two objects compared are the same object, then return true directly if (this == obj){ //this represents the object that calls the equals method, obj is the actual parameter in the method return true; } //Type judgment if (obj instanceof Person){ //obj is Person, we compare //Carry downward transformation (i.e., obj is converted to Person); because I need to get the various attributes of obj, if I don't transform, I can't get it Person p = (Person) obj; return () && == && == ; } //If it is not a person, it will directly return false; you can't compare one person with one dog return false; } public Person(String name, int age, char gender) { = name; = age; = gender; } public String getName() { return name; } public void setName(String name) { = name; } public int getAge() { return age; } public void setAge(int age) { = age; } public char getGender() { return gender; } public void setGender(char gender) { = gender; } }
Tips:
Usage of instanceof:result = object instanceof class
instanceof is the object on the left and the class on the right; return true when the object is an object created by a class or subclass on the right; otherwise, return false.
This is the article about the understanding and usage of the equals() method in Java. For more relevant content on the use of the equals() method, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!