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.
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...
To compare the values in the arrays, use Arrays.equals(char[], char[])
.
System.out.println(Arrays.equals(d, e));
Arrays do not override Object#equals()
. Use:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With