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
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);
Use this:
return Arrays.equals(perm1, perm2)
Instead of this:
return perm1.equals(perm2);
Please have to look this
boolean t = Arrays.equals(nir1,nir2)
Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case
Use Arrays.equals
instead of array1.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 means array1 == array2
which is not true in this case.
public static boolean perm (String s, String t){
if (s.length() != t.length()) {
return false;
}
char[] perm1 = s.toCharArray();
Arrays.sort(perm1);
char[] perm2 = t.toCharArray();
Arrays.sort(perm2);
return Arrays.equals(perm1, perm2);
}
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.