Java comparing Arrays

六眼飞鱼酱① 提交于 2021-02-16 15:57:09

问题


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:


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




回答2:


You should try Arrays.deepEquals(a, b)




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




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


来源:https://stackoverflow.com/questions/7869050/java-comparing-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!