10

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

1
  • Added some method declaration parts (public static ...) - otherwise it looked for me as ruby method call with passed block :-) Commented Jan 22, 2013 at 15:51

4 Answers 4

17

ArrayUtils.isEquals() from Apache Commons does exactly that. It also handles multi-dimensional arrays.

Sign up to request clarification or add additional context in comments.

3 Comments

Is 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
Okay - 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.
ArrayUtils.isEquals() is now deprecated in favor of java.util.Objects.deepEquals().
11

You should try Arrays.deepEquals(a, b)

Comments

5

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.

Comments

1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.