4
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.

Justin
  • 24,288
  • 12
  • 92
  • 142
Nik
  • 195
  • 3
  • 5
  • 12

2 Answers2

15

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));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I confused it with String's equal method, I feel so dumb. Thanks a lot! – Nik Nov 08 '13 at 17:39
  • 3
    This has always seemed unhelpful (of java) to me; if people want the `==` they can use `==`, I understand it as a default but I cannot see why it wasn't overridden in this case (or made not available at all as arrays are special) – Richard Tingle Nov 08 '13 at 17:47
11

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.

Community
  • 1
  • 1
nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • @Quincunx If you encode the URL using `%29` and `%28` for parentheses it should process correctly. Thanks for mentioning this! – nanofarad Nov 08 '13 at 17:42
  • Thanks for the tip (I deleted my comment because you included it in your post; thought you found it elsewhere) – Justin Nov 08 '13 at 17:43