When comparing arrays in Java, are there any differences between the following 2 statements?
array1.equals(array2);
Arrays.equals(array1, array2);
And if so, what are they?
When comparing arrays in Java, are there any differences between the following 2 statements?
array1.equals(array2);
Arrays.equals(array1, array2);
And if so, what are they?
The
equals()
of arrays is inherited fromObject
, so it does not look at the contents of the arrrays, it only considers each array equal to itself.The
Arrays.equals()
methods do compare the arrays' contents. There's overloads for all primitive types, and the one for objects uses the objects' ownequals()
methods.Here is the output:
Seeing this kind of problem I would personally go for
Arrays.equals(array1, array2)
as per your question to avoid confusion.Look inside the implementation of the two methods to understand them deeply:
while:
Arrays inherit
equals()
fromObject
and hence compare only returns true if comparing an array against itself.On the other hand,
Arrays.equals
compares the elements of the arrays.This snippet elucidates the difference:
See also
Arrays.equals()
. Another static method there may also be of interest:Arrays.deepEquals()
.array1.equals(array2)
is the same asarray1 == array2
, i.e. is it the same array. As @alf points out it's not what most people expect.Arrays.equals(array1, array2)
compares the contents of the arrays.Similarly
array.toString()
may not be very useful and you need to useArrays.toString(array)
.It's an infamous problem:
.equals()
for arrays is badly broken, just don't use it, ever.That said, it's not "broken" as in "someone has done it in a really wrong way" — it's just doing what's defined and not what's usually expected. So for purists: it's perfectly fine, and that also means, don't use it, ever.
Now the expected behaviour for
equals
is to compare data. The default behaviour is to compare the identity, asObject
does not have any data (for purists: yes it has, but it's not the point); assumption is, if you needequals
in subclasses, you'll implement it. In arrays, there's no implementation for you, so you're not supposed to use it.So the difference is,
Arrays.equals(array1, array2)
works as you would expect (i.e. compares content),array1.equals(array2)
falls back toObject.equals
implementation, which in turn compares identity, and thus better replaced by==
(for purists: yes I know aboutnull
).Problem is, even
Arrays.equals(array1, array2)
will bite you hard if elements of array do not implementequals
properly. It's a very naive statement, I know, but there's a very important less-than-obvious case: consider a 2D array.2D array in Java is an array of arrays, and arrays'
equals
is broken (or useless if you prefer), soArrays.equals(array1, array2)
will not work as you expect on 2D arrays.Hope that helps.