I have two object arrays like so:
Object[] array1 = {0, 1, 2, 3};
Object[] array2 = {0, 1, 2, 3};
I would like to know if the arrays are equal. I'm defining equal as every value in array1 is the same as the value in that position in the array2. So these two arrays would be equal.
What is the best why to find out if these two arrays are equal?
if(array1 == array2)
is not a deep equals so that won't work and I don't know if looping over each element and comparing them is the best and most efficient way to solve this problem. Does anyone have any better suggestions?
Edit: I needed an equals that can go into nested arrays.
To compare arrays, I would use the Arrays.equals method:
Use
Arrays.deepEquals()
. This does the same job asArrays.equals()
but also works with nested arrays.java.util.Arrays.equals
array1.equals(array2)
should give you what you are looking for.In the example you've posted the arrays will actually contain
Integer
objects. In that case,Arrays.equals()
is enough. However, if your arrays contain some objects of yours, you have to implementequals()
in your class so thatArrays.equals()
workGenerally utility class java.util.Arrays is very usefull.