比较Java的阵列
int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
为什么m和t假?在Java中比较2个阵列的正确方法是什么?
int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
Why are both m and t false? What is the correct way to compare 2 arrays in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 Arrays.Quals 方法。例子:
Use Arrays.equals method. Example:
原因
t
返回false是因为数组使用object
的可用方法。由于这是在使用对象#equals()
,因此它返回false,因为nir1
和nir2
不是同一对象。在
m
的情况下,相同的想法也存在。对象#tostring()
打印出对象标识符。就我而言,当我将它们打印出来并检查它们时,结果当然是不一样的。
Coolbeans是正确的;使用静态
arrays.equals()
方法进行比较。The reason
t
returns false is because arrays use the methods available to anObject
. Since this is usingObject#equals()
, it returns false becausenir1
andnir2
are not the same object.In the case of
m
, the same idea holds.Object#toString()
prints out an object identifier. In my case when I printed them out and checked them, the result wasWhich are, of course, not the same.
CoolBeans is correct; use the static
Arrays.equals()
method to compare them.使用
arrays.quals
而不是array1.equals(array2)
。arrays.equals(array1,array2)
将检查两个数组的内容,然后将检查参考。array1.equals(array2)
简单地表示array1 == array2
在这种情况下是不正确的。Use
Arrays.equals
instead ofarray1.equals(array2)
.Arrays.equals(array1, array2)
will check the content of the two arrays and the later will check the reference.array1.equals(array2)
simply meansarray1 == array2
which is not true in this case.我只是想指出失败的原因:
数组不是对象,它们是原始类型。
打印NIR1.ToString()时,您会以文本形式获得NIR1的Java标识符。由于NIR1和NIR2分别分配,因此它们是唯一的,这将为ToString()产生不同的值。
出于相同的原因,两个阵列也不相等。它们是单独的变量,即使它们具有相同的内容。
就像其他海报所建议的那样,要走的方法是使用数组类:
对于
复杂的数组。
另外,对于平等:
I just wanted to point out the reason this is failing:
arrays are not Objects, they are primitive types.
When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().
The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.
Like suggested by other posters, the way to go is by using the Arrays class:
and
for complex arrays.
Also, for equality:
使用以下内容:
代替:
请必须查看 this
Use this:
Instead of this:
Please have to look this