比较 Java 中的两个基元数组? [英] Compare two arrays of primitives in Java?

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

问题描述

我知道 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 :)

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

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