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

查看:147
本文介绍了比较两个数组的基元在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;
}


推荐答案

if (a == b)
    return true;

这不仅捕获两个null情况,还 。

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天全站免登陆