標籤:
==對於基本類型,比較的是他們的值是否相等,對於參考型別,比較的是記憶體中,他們是否都指向記憶體中同一個對象.
所有類都繼承Object類的equals()方法,此方法預設的實現使用==比較,一些類重載了equals()方法,從而比較的是對象的內容.
We’ve seen that primitive types and reference types differ significantly in the way
they are assigned to variables, passed to methods, and copied. The types also differ
in the way they are compared for equality. When used with primitive values, the
equality operator (==) simply tests whether two values are identical (i.e., whether
they have exactly the same bits). With reference types, however, == compares refer‐
ences, not actual objects. In other words, == tests whether two references refer to the
same object; it does not test whether two objects have the same content.
When working with reference types, there are two kinds of equality: equality of ref‐
erence and equality of object. It is important to distinguish between these two kinds
of equality. One way to do this is to use the word “identical” when talking about
equality of references and the word “equal” when talking about two distinct objects
that have the same content. To test two nonidentical objects for equality, pass one of
them to the equals() method of the other:
All objects inherit an equals() method (from Object), but the default implementa‐
tion simply uses == to test for identity of references, not equality of content. A class
that wants to allow objects to be compared for equality can define its own version of
the equals() method. Our Point class does not do this, but the String class does,
as indicated in the code example. You can call the equals() method on an array, but
it is the same as using the == operator, because arrays always inherit the default
equals() method that compares references rather than array content. You can com‐
pare arrays for equality with the convenience method java.util.Arrays.equals().
java ==和equals() --Java in a Nutshell, 6th