java ==和equals()  --Java in a Nutshell, 6th

來源:互聯網
上載者:User

標籤:

==對於基本類型,比較的是他們的值是否相等,對於參考型別,比較的是記憶體中,他們是否都指向記憶體中同一個對象.
所有類都繼承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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.