比较Java中的两个基元数组?

2022-01-25 00:00:00 arrays compare java primitive-types

我知道 Arrays.deepEquals(Object[], Object[]) 但这不适用于原始类型(由于数组和自动装箱的限制,请参阅 此相关帖子).

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.

但是,对于更简单的替代方法 - 使用 Arrays.equals 对每个原始类型都有重载.(实现与您的非常相似,除了它将数组长度提升到循环之外.在 .NET 上,这可能是一种反优化,但我猜 JRE 库实现者可能更了解 JVM :)

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

相关文章