comparing arrays in java

2019-01-19 06:11发布

问题:

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?

回答1:

Use Arrays.equals method. Example:

boolean b = Arrays.equals(nir1, nir2); //prints true in this case


回答2:

The reason t returns false is because arrays use the methods available to an Object. Since this is using Object#equals(), it returns false because nir1 and nir2 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 was

nir1 = [I@3e25a5
nir2 = [I@19821f

Which are, of course, not the same.

CoolBeans is correct; use the static Arrays.equals() method to compare them.



回答3:

boolean t = Arrays.equals(nir1,nir2)


回答4:

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:

Arrays.toString(nir1);

and

Arrays.deepToString(nir1);

for complex arrays.

Also, for equality:

Arrays.equals(nir1,nir2);