Home >Java >javaTutorial >Java reference variable equality and object equality
The "==" and equals() methods are often used in Java to determine whether objects are equal. Let's talk about how to determine whether two objects are equal.
Every object on the heap will have its reference variable. If there is no object referenced by the reference variable, the GC on the heap will come back to chat with it.
Comparison of "==", both sides of the symbol are reference variables of the object. If the comparison returns true, it means that the reference variables on both sides of the symbol refer to the same object, because "==" compares the reference variables in the reference variable. value, so "==" comparison is a reference comparison.
But what if two different objects are compared to see if they are the same in meaning? For example, two Student objects have the same instance variables name and sex. Can we consider them to be two equal objects?
equals() method
This requires the use of the equals() method. First of all, what we need to know is that the equals() method is defined in Object, the parent class of all classes. The comparison method of equals in Object is similar to "==". It will return true only when the two objects being compared are the same object, otherwise it will return false. So we will override the equals() method in the class to check whether two different objects on the heap are the same in meaning. Before overriding the equals() method, we have to override the hashcode() method because we then call equals. () method, it will first compare the values returned by hashcode() of the two objects. If they are not the same, it will return false. I think when we override the hashcode() method, all objects of the same type will be returned. The same hashcode value, by declare a result variable value in the HashCode () method, for example,
[code = "java"] public int hashcode () {
int result = 17;
result = 31*result++ result+ name! =null?name.hashCode():0;
result=31*result+region!=null?region.hashCode():0;
result=31*result+position!=null?position.hashCode():0 ; U Return Result;
}
then return to the Equals () method to determine whether the instance variables of the two objects are the same. To write the equals() method, you need to look at the specific class, because the instance variables of each class are different. (If you create a new object without a special constructor, the instance variables will have default values, so the two newly created different types are also equal. , because the instance variables all have the same default value).