2016-02-28 85 views
0

我有這個問題,但我不知道它在哪裏出錯。與陣列相關

int[] first = new int[2]; 
first[0] = 3; 
first[1] = 7; 
int[] second = new int[2]; 
second[0] = 3; 
second[1] = 7; 

// print the array elements 
System.out.println("first  = [" + first[0] + ", " + first[1] + "]"); 
System.out.println("second = [" + second[0] + ", " + second[1] + "]"); 

// see if the elements are the same 
if (first[] = second[]) { 
    System.out.println("They contain the same elements."); 
} else { 
    System.out.println("The elements are different."); 
} 

預期出放應該是這樣的,例如:

first = [3, 7] 
second = [3, 7] 
They contain the same elements. 
+0

評論http://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java –

回答

0

這裏是解決

System.out.println("first = " + Arrays.toString(first); 
System.out.println("second = " + Arrays.toString(second); 

,並在後面的代碼

if (Arrays.equals(first,second)) { 
    System.out.println("They contain the same elements."); 
} else { 
    System.out.println("The elements are different."); 
} 
+0

你能解釋我如何Arrays.toString()的作品? –

+0

它給出了你的數組的字符串表示,例如,如果你有int [] arr = {1,2,3}; Arrays.toString()會給你下面的輸出[1,2,3] – Jorgovanka

0

在java中,陣列是對象,==(在問題假設=是一個錯字)只檢查是否兩個參考指向同一個對象,這顯然不是這裏的情況。

爲了比較這樣的數組,我們需要對它們進行迭代並檢查兩個元素是否在相同的位置。

0

要打印的陣列的元素,必須輸入在System.out.println()方法的元件本身:

System.out.println("First: " + first[0] + ", " + first[1]); 

,並評價兩個數組是否包含相同的元素,則具有由元件對其進行比較元件:

if(first[0] == second[0] && first[1] == second[1]) /*arrays are the same*/; 

通常在比較數組時會使用循環。

0

我將與third變量擴展你的榜樣,所以你可以更好地瞭解

int[] first = new int[2]; 
    first[0] = 3; 
    first[1] = 7; 
    int[] second = new int[2]; 
    second[0] = 3; 
    second[1] = 7; 
    int[] third = first; 

    if (Arrays.equals(first, second)) 
     System.out.println("first && second contain the same elements."); 
    else 
     System.out.println("first && second elements are different."); 

    if (Arrays.equals(first, third)) 
     System.out.println("first && third contain the same elements."); 
    else 
     System.out.println("first && third elements are different."); 

    if (first == second) 
     System.out.println("first && second point to the same object."); 
    else 
     System.out.println("first && second DO NOT point to the same object."); 

    if (first == third) 
     System.out.println("first && third point to the same object."); 
    else 
     System.out.println("first && third DO NOT point to the same object."); 

輸出:

first && second contain the same elements. 
first && third contain the same elements. 
first && second DO NOT point to the same object. 
first && third point to the same object. 

==等於運算符只會檢查它們是否是相同的對象(第三個是第一個別名,因此它們都指向相同的對象)。

雖然Arrays.equals(a, b)將比較兩個數組中的所有元素,如果它們全部匹配,則返回true。