Java中數組的比較的真相

來源:互聯網
上載者:User


最近在去除冗餘代碼的時候,稍微比較了一下兩個數組,結果和我預想中的不一樣,簡單總結一下。

比如比較兩個byte[]數組,在保證其中一個不為null的情況下,這樣就能判斷出其內容是否相同。其實不然,比如看下列代碼。

import java.util.Arrays;  public class ArrayCompareRoot {public static void main(String[] args) {final String s = "Google";byte[] content1 = s.getBytes();byte[] content2 = s.getBytes();compareAddress(content1, content2);compareContent(content1, content2);compare(content1, content2);compareObjectArrays();} private static final void compareAddress(byte[] value1, byte[] value2) {System.out.println("value1 compare value2 by address = " + (value1 == value2));} private static final void compareContent(byte[] value1, byte[] value2) {System.out.println("value1 commpare value2 by content = " + (value1.equals(value2)));} private static final void compare(byte[] value1, byte[] value2) {System.out.println("value1 compare value2 = " + Arrays.equals(value1, value2));} private static final void compareObjectArrays() {Book[] books1 = new Book[1];Book[] books2 = new Book[1];Book book = new Book();books1[0] = book;books2[0] = book;System.out.println("compare object array = " + (books1.equals(books2)));System.out.println("compare object arrays= " + Arrays.equals(books1, books2));} static class Book { @Overridepublic boolean equals(Object obj) {return true;} @Overridepublic int hashCode() {return 1;} }}

運行結果如下:
value1 compare value2 by address = false
value1 commpare value2 by content = false
value1 compare value2 = true
compare object array = false
compare object arrays= true
仔細研究一下三個比較方法就明白了。
compareAddress()只是單純比較兩個數組的記憶體位址。
compareContent()雖然調用了equals的方法,但是實際上數組調用的equals方法是Object的equals方法。而Object的equals方法內容如下:

public boolean equals(Object obj) {return (this == obj);}

看到源碼後發現,這個方法也是比較記憶體位址。
compare方法調用的是一個工具類的方法,及Arrays.equals(byte[],byte[])方法,其實現邏輯為:

public static boolean equals(byte[] a, byte[] a2) {        if (a==a2)            return true;        if (a==null || a2==null)            return false;         int length = a.length;        if (a2.length != length)            return false;         for (int i=0; i<length; i++)            if (a[i] != a2[i])                return false;         return true;}

compareObjectArrays 比較了兩個對象數組,結果也是一樣的。
個人理解數組就是特殊的Object,它具有Object的介面,不增加也不減少。
注意,在重寫equals方法的同時,應該重寫hashCode()方法。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.