Compare two arrays of primitives in Java?(比较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中的两个基元数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较Java中的两个基元数组?


基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01