This question already has an answer here:
这个问题在这里已有答案:
- equals vs Arrays.equals in Java 8 answers
- 在Java 8答案中等于vs Arrays.equals
public static void main(String[] args)
{
char [] d = {'a','b','c','d'};
char [] e = {'d','c','b','a'};
Arrays.sort(d);
Arrays.sort(e);
System.out.println(e); //console : abcd
System.out.println(d); //console : abcd
System.out.println(d.equals(e)); //console : false
}
Why are the arrays unequal? I'm probably missing something but it's driving me crazy. Isn't the result supposed to be true? And yes I have imported java.util.Arrays.
为什么阵列不相等?我可能错过了一些东西,但这让我发疯了。结果应该是真的吗?是的,我已导入java.util.Arrays。
2 个解决方案
#1
15
Isn't the result supposed to be true?
结果应该是真的吗?
No. You're calling equals
on two different array references. Arrays don't override equals
, therefore you get reference equality. The references aren't equal, therefore it returns false...
不。你在两个不同的数组引用上调用equals。数组不会覆盖等于,因此您获得引用相等。引用不相等,因此它返回false ...
To compare the values in the arrays, use Arrays.equals(char[], char[])
.
要比较数组中的值,请使用Arrays.equals(char [],char [])。
System.out.println(Arrays.equals(d, e));
#2
11
Arrays do not override Object#equals()
. Use:
数组不会覆盖Object#equals()。使用:
Arrays.equals(d, e);
instead to perform a value-based comparison.
而是执行基于价值的比较。
However:
然而:
Arrays.equals
does not work as expected for multidimensional arrays. It will compare the references of the first level of arrays instead of comparing all levels. Refer to this comment, or use Arrays.deepEquals
in the same manner.
Arrays.equals不能像多维数组那样工作。它将比较第一级数组的引用,而不是比较所有级别。请参阅此注释,或以相同方式使用Arrays.deepEquals。
#1
15
Isn't the result supposed to be true?
结果应该是真的吗?
No. You're calling equals
on two different array references. Arrays don't override equals
, therefore you get reference equality. The references aren't equal, therefore it returns false...
不。你在两个不同的数组引用上调用equals。数组不会覆盖等于,因此您获得引用相等。引用不相等,因此它返回false ...
To compare the values in the arrays, use Arrays.equals(char[], char[])
.
要比较数组中的值,请使用Arrays.equals(char [],char [])。
System.out.println(Arrays.equals(d, e));
#2
11
Arrays do not override Object#equals()
. Use:
数组不会覆盖Object#equals()。使用:
Arrays.equals(d, e);
instead to perform a value-based comparison.
而是执行基于价值的比较。
However:
然而:
Arrays.equals
does not work as expected for multidimensional arrays. It will compare the references of the first level of arrays instead of comparing all levels. Refer to this comment, or use Arrays.deepEquals
in the same manner.
Arrays.equals不能像多维数组那样工作。它将比较第一级数组的引用,而不是比较所有级别。请参阅此注释,或以相同方式使用Arrays.deepEquals。