0

How would I compare two arrays for exact equality.

Originally I was thinking:

int[] array1 = new int[]{2, 0};
int[] array2 = new int[]{2, 0};
if(array1 == array2)
//do something

this doesn't work. Can someone explain what it is that I am comparing if not the values inside the array? Also how do I compare the two arrays to check if they are identical?

Crouton
  • 33
  • 4

1 Answers1

0

You should use Arrays.equals(array1,array2), which will compare the elements of the two arrays to each other, in the order they appear.

When you compare the arrays with == you are comparing references, so it will only return true is you are comparing an object to itself (for example, array1 == array1).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Oh ok I have used .equals before but I thought it was only good for comparing strings. Thanks! – Crouton Feb 08 '15 at 07:49
  • 1
    @Crouton Actually, it's not the same as equals for Strings. array1.equals(array2) won't work either, since it uses the default implementation of equals in Object class. You must use the static method in the Arrays class. – Eran Feb 08 '15 at 07:53
  • yeah I just realized it doesn't work the same. Thanks for the correction on my part. – Crouton Feb 08 '15 at 07:55