比较原语的两个数组在Java中? [英] Compare two arrays of primitives in Java?

查看:224
本文介绍了比较原语的两个数组在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Arrays.deepEquals(对象[],对象[]),但这并不对基本类型(数组和自动装箱由于限制问题,请参见<一个href=\"http://stackoverflow.com/questions/517751/java-generic-method-but-array-of-primitive-data-types-does-not-autobox\">this相关帖子)。

考虑到这一点,这是最有效的方法?

 布尔byteArrayEquals(字节[]一,字节[] B){
    如果(A == NULL和放大器;和b == NULL)
        返回true;    如果(A == NULL || b == NULL)
        返回false;    如果(则为a.length!= b.length个)
        返回false;    的for(int i = 0; I&LT;则为a.length;我++){
        如果(A [I]!= B [I])
            返回false;
    }
    返回true;
}


解决方案

更改您的第一个比较是:

 如果(A == B)
    返回true;

这不仅抓住了两个零的情况下,也有一个数组比较自己的情况。

然而,对于一个简单的替代 - 使用<一href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#equals%28byte%5B%5D,%20byte%5B%5D%29\"><$c$c>Arrays.equals它针对每个基本类型的重载。 (实现非常相似,你的,除了它吊数组长度圈外.NET的,可以防优化,但是我想JRE库实现者可能知道JVM的更好。)

I know about Arrays.deepEquals(Object[], Object[]) but this doesn't work for primitive types (due limitations of arrays and autoboxing, see this related post).

With that in mind, is this the most efficient approach?

boolean byteArrayEquals(byte[] a, byte[] b) {
    if (a == null && b == null)
        return true;

    if (a == null || b == null)
        return false;

    if (a.length != b.length)
        return false;

    for (int i = 0; i < a.length; i++) {
        if (a[i] != b[i])
            return false;
    }
    return true;
}

解决方案

Change your first comparison to be:

if (a == b)
    return true;

This not only catches the "both null" cases, but also "compare an array to itself" case.

However, for a simpler alternative - use Arrays.equals which has overloads for each primitive type. (The implementation is very similar to yours, except it hoists the array length out of the loop. On .NET that can be an anti-optimization, but I guess the JRE library implementors probably know better for the JVM :)

这篇关于比较原语的两个数组在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆