= The operator is used to compare whether the values of variables are equal. A better understanding is:
Int A = 10;
Int B = 10;
Then a = B will be true.
But what is hard to understand is:
String A = new string ("foo ");
String B = new string ("foo ");
If a = B, false is returned.
According to the previous post, object variables are actually a reference. Their values point to the memory address of the object, not the object itself. Both A and B use the new operator, which means that two strings with content "foo" will be generated in the memory. Since they are "two" strings, they are naturally located at different memory addresses. The values of A and B are actually two different memory address values. Therefore, the result is false when the "=" operator is used. It is true that the content of objects A and B is "foo" and should be "equal", but the = operator does not involve the comparison of object content.
The comparison of object content is exactly what the equals method does.
Let's take a look at how the equals method of the object is implemented:
Boolean equals (Object O ){
Return this = O;
}
The = Operator is used by default for object objects. Therefore, if your own class does not overwrite the equals method, you will get the same result when using equals and =. We can also see that the equals method of the object does not meet the goal that the equals method should achieve: compare whether the content of the two objects is equal. Because the answer should be determined by the class creator, the object leaves this task to the class creator.
Take a look at the next extreme class:
Class monster {
Private string content;
...
Boolean equals (Object another) {return true ;}
}
I overwrite the equals method. This implementation will always return true regardless of the content of the monster instance.
Therefore, when you use the equals method to determine whether the object content is equal, do not take it for granted. Because you may think they are equal, and the authors of this class do not think so, and the implementation of the equals method of the class is controlled by him. If you need to use the equals method or any hash code-based set (hashset, hashmap, hashtable ), check the Java Doc to see how the equals logic of this class is implemented.