Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't these two arrays equal? [duplicate]

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.

like image 521
Nik Avatar asked Nov 28 '22 21:11

Nik


2 Answers

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));
like image 129
Jon Skeet Avatar answered Dec 05 '22 05:12

Jon Skeet


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.

like image 33
nanofarad Avatar answered Dec 05 '22 04:12

nanofarad