java Java比较数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7869050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:46:47  来源:igfitidea点击:

Java comparing Arrays

javaarraysprimitive

提问by DD.

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

我想在没有所有 instanceof 检查的情况下执行此操作....

回答by Tomasz Nurkiewicz

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

来自Apache Commons 的ArrayUtils.isEquals()正是这样做的。它还处理多维数组。

回答by Eng.Fouad

You should try Arrays.deepEquals(a, b)

你应该试试 Arrays.deepEquals(a, b)

回答by Miquel

Arrays utilities class could be of help for this:

Arrays 实用程序类可能对此有所帮助:

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html

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.

比较对象数组。

回答by Peter Walser

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

如果数组类型未知,则不能简单地强制转换为Object[],因此不能使用 中的方法 ( equals, deepEquals) java.util.Arrays
但是,您可以使用反射来获取数组的长度和项目,并递归地比较它们(项目本身可能是数组)。

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