Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java comparing Arrays

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

like image 329
DD. Avatar asked Oct 23 '11 20:10

DD.


People also ask

How do you compare 2 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).

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do I compare two indexes in an array in Java?

Emanuel Maliaño when comparing String values in Java you need to use the equals() method. The use of the comparison operator "==" will only return true if they are the same object in memory which is not guaranteed even with a direct comparison of literal Strings.

How do I compare two double arrays in Java?

Arrays. equals(double[] a, double[] a2) method returns true if the two specified arrays of doubles are equal to one another. Two arrays are equal if they contain the same elements in the same order.


1 Answers

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);
}
like image 184
Peter Walser Avatar answered Oct 20 '22 21:10

Peter Walser