comparing arrays in 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());

Why are both m and t false? What is the correct way to compare 2 arrays in Java?


Use Arrays.equals method. Example:

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

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.


boolean t = Arrays.equals(nir1,nir2)