In the interview, often asked euqals () and = = What is the difference, estimated that a lot of people will answer: the former is the comparative value, the latter is the comparison of memory address, in fact, this only to the general bar, I feel.
First = = really is the memory address of the object of comparison, this is undoubtedly, and euqals () it?
In fact, Euqals () is a method in the object class, view the source code:
public boolean equals (Object o) { return this = = O; }
The original Euqals () is also done = = run. Is it not the same as many people think? At least not the same as I thought.
And why would you say Euqals () is a value comparison? In fact euqals () This method can be rewritten, and String,integer rewrite it.
Let's take a look at the Euqals () of String,
public boolean equals (Object anobject) { if (this = = AnObject) { return true; } if (anobject instanceof string) { string anotherstring = (string) anobject; int n = value.length; if (n = = anotherString.value.length) { char v1[] = value; Char v2[] = Anotherstring.value; int i = 0; while (n--! = 0) { if (v1[i]! = V2[i]) return false; i++; } return true; } } return false; }
The core is a comparison of each character.
And look at the euqals of the Integer ()
@Override public Boolean equals (Object o) { return (o instanceof integer) && ((Integer) o). Value = = Val UE); }
The core is also a value comparison.
Therefore, the following conclusions are drawn:
1. In the absence of rewrite euqals (), = = and euqals () The result is the same, is the memory address comparison.
2. In the String,integer class, because Euqals () is overridden, euqals () is a value comparison, and = = is still a memory address comparison.
"Android General advanced" reference data type euqals () and = = Get the same result