我有这个问题,但我不知道它出错了。
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 :(得分:0)
在java中,数组是Objects,而==
(假设=在问题中是一个拼写错误)只检查两个引用是否指向同一个对象,这显然不是这里的情况。
为了比较像这样的数组,我们需要迭代它们并检查它们在相同位置是否具有相同的元素。
答案 1 :(得分: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*/;
通常在比较数组时会使用循环。
答案 2 :(得分: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.");
}
答案 3 :(得分: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。