2016-02-28 91 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。