Java comparing Arrays
Solution 1
ArrayUtils.isEquals() from Apache Commons does exactly that. It also handles multi-dimensional arrays.
Solution 2
You should try Arrays.deepEquals(a, b)
Solution 3
Arrays utilities class could be of help for this:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html
There is a method:
equals(Object[] a, Object[] a2)
That compares arrays of objects.
Solution 4
If the array type is unknown, you cannot simply cast to Object[]
, and therefore cannot use the methods (equals
, deepEquals
) in java.util.Arrays
.
You can however use reflection to get the length and items of the arrays, and compare them recursively (the items may be arrays themselves).
Here's a general utility method to compare two objects (arrays are also supported), which allows one or even both to be null:
public static boolean equals (Object a, Object b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.getClass().isArray() && b.getClass().isArray()) {
int length = Array.getLength(a);
if (length > 0 && !a.getClass().getComponentType().equals(b.getClass().getComponentType())) {
return false;
}
if (Array.getLength(b) != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (!equals(Array.get(a, i), Array.get(b, i))) {
return false;
}
}
return true;
}
return a.equals(b);
}
DD.
Updated on June 04, 2022Comments
-
DD. almost 2 years
I have two Arrays of unknown type...is there a way to check the elements are the same:
public static boolean equals(Object a , Object b) { if (a instanceof int[]) return Arrays.equals((int[]) a, (int[])b); if (a instanceof double[]){ ////etc }
I want to do this without all the instanceof checks....
-
Vladimir over 11 yearsIs there any benefit to use non-core library for this? If not it's better to go with standard Arrays.equals instead. I just don't wont to confuse any people looking to the selected answer. It feels more naturally to use standard method than the one from Apache Commons. I choose Arrays.equals instead
-
Vladimir over 11 yearsOkay - looks like the issue is that with Arrays.equals and Arrays.deepEquals you can't pass arrays as object like in ArrayUtils.isEquals - got it now.
-
izilotti about 2 years
ArrayUtils.isEquals()
is now deprecated in favor ofjava.util.Objects.deepEquals()
.