Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array Comparison

Tags:

java

arrays

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[]) {
         ...
like image 961
BlairHippo Avatar asked Mar 22 '10 15:03

BlairHippo


People also ask

How do you compare 2 arrays in Java?

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)

Can we use == to compare arrays in Java?

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).

Can you compare array elements 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.


2 Answers

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.

like image 61
polygenelubricants Avatar answered Oct 06 '22 20:10

polygenelubricants


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...

like image 43
Michael Borgwardt Avatar answered Oct 06 '22 20:10

Michael Borgwardt