The difference between “= =” and equals methods
When writing code, you often use "= =" and equsls. You rarely think about the difference between them. Now let's summarize.
I==
The "= =" operator is specially used to compare whether the values of two variables are equal, that is, to compare whether the values stored in the memory corresponding to the variables are the same.
To compare whether two basic types of data or two reference variables are equal, you can only use the "= =" operator. If the data pointed to by a variable is of object type,
Then, two blocks of memory are involved. The object itself occupies one block of memory (heap memory) and the variable also occupies one block of memory, for example:
The variable object occupies one memory and new object () occupies another. At this time, the value stored in the memory corresponding to the variable object is the first address of the memory occupied by the object.
For variables that point to object types, if you want to compare whether two variables point to the same object, you need to see whether the values in memory corresponding to the two variables are equal. In this case, you need to use the = = operator for comparison.
2、 Equals
If a class does not define its own equals method, it will inherit the equals method of object class. The implementation code of the equals method of object class is as follows:
The equals method is used to compare whether the contents of two independent objects are the same. The two objects it compares are independent. For example, for the following code:
In the above code, two new statements create two objects, and then point to one of them with variables A and B, which are two different objects
Their first addresses are different, that is, the values stored in a and B are different, so the expression a = = B will return false. The contents of the two objects are the same, so the expression A. equals (b) will return true.
In daily code writing, we often have to compare whether the passed string content is correct or not. Remember that string comparisons basically use the equals method.