1.equals ()
In the beginner Java, many people will say that when comparing objects, = = is the comparison of the address, equals () is the content of the comparison object, who said?
Look at the definition of the Equals () method in the object class:
public boolean equals(Object obj){
return (this == obj);
}
Is this a comparative content? is obviously the comparison pointer (address) Mody ...
But why is there a saying that equals is the content of comparison?
Because the Equals () method of the object class has already been overloaded (overriding) in an encapsulated class such as String, double, and then there is another calculation formula, which is a comparison of the contents.
For example, in the String class:
public int hashCode() {
int h = hash;
if (h == 0) {
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
2.hashCode ()
The definition in the object class is:
public native int hashcode ();
is a local method that returns the address value of an object.
However, in the same way, this method is overridden in a wrapper class such as String. Method call to get an int value from a calculated formula
3. The relationship between the two
① two obj, if equals () equal, hashcode () must be equal
② two obj, Equals () is not necessarily equal if hashcode () is equal
Reason: From the perspective of hashing, different objects compute hash code, may cause conflict, we must remember the data structure of the conflict solution bar
But for this design, with two functions, the individual's understanding is to be more efficient when comparing two objects.
You can consider that in a Java collection, the rules for determining whether two objects are equal are:
The first step, if Hashcode () is equal, then look at the second step, otherwise not equal;
The second step is to see if equals () are equal, and if they are equal, the two obj are equal or unequal.
Why did you do that? The personal understanding is to let the proper function complete the proper function, after all, hashcode () is faster than equals () in some way.