Working within Java, let's say I have two objects that, thanks to obj.getClass().isArray()
, I know are both arrays. Let's further say that I want to compare those two arrays to each other -- possibly by using Arrays.equals
. Is there a graceful way to do this without resorting to a big exhaustive if/else tree to figure out which flavor of Arrays.equals
needs to be used? I'm looking for something that's less of an eyesore than this:
if (obj1 instanceof byte[] && obj2 instanceof byte[]) {
return Arrays.equals((byte[])obj1, (byte[])obj2);
}
else if (obj1 instanceof boolean[] && obj2 instanceof boolean[]) {
...
Java Arrays class provides the equals() method to compare two arrays. It iterates over each value of an array and compares the elements using the equals() method. Syntax: public static boolean equals(int[] a1, int[] a2)
Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
You can use reflection.
public static boolean arrayEquals(Object arr1, Object arr2) throws Exception {
Class<?> c = arr1.getClass();
if (!c.getComponentType().isPrimitive()) {
c = Object[].class;
}
Method m = Arrays.class.getMethod("equals", c, c);
return (Boolean) m.invoke(null, arr1, arr2);
}
Reflection is only used to find the right method at run-time without the eyesore you're looking to avoid; the actual Arrays.equals
method should run pretty fast.
Obviously production version needs more robust exception handling. You may also want to use deepEquals(Object[], Object[])
instead of equals(Object[], Object[])
for non-primitive arrays.
I'm afraid the only alternative would be to use reflection, which would be nearly as ugly.
Arrays.getClass()
.getMethod("equals", new Class[]{obj1.getClass(), obj2.getClass()})
.invoke(null, new object[]{obj1, obj2});
Not tested, could fail in all kinds of ways, needs lots of exception handling...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With