比较 Java 中的两个基元数组?
我知道 Arrays.deepEquals(Object[], Object[]) 但这不适用于原始类型(由于数组和自动装箱的限制,请参阅 此相关帖子)。
考虑到这一点,这是最有效的方法吗?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将您的第一个比较更改为:
这不仅捕获“均为空”的情况,而且还捕获“将数组与其自身进行比较”的情况。
但是,对于更简单的替代方案 - 使用
Arrays.equals
它对每个基本类型都有重载。 (该实现与您的实现非常相似,只是它将数组长度提升到循环之外。在 .NET 上,这可能是一种反优化,但我猜 JRE 库实现者可能更了解 JVM :)Change your first comparison to be:
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 :)我认为最有效的应该是使用 Arrays 类,因为它们可能会更巧妙地实现。 所以在这种情况下,使用
I think the most efficient should be to use the helper methods in the Arrays class, because they might be implemented more cleverly. So in this case, use
我不知道这是否会对任何人有帮助,但这似乎有效:
显然
array.equals(otherArray)
做了一个array == otherArray
,而不是你做的会期望。I don't know if this will help anyone, but this seems to be working:
Apparently
array.equals(otherArray)
does aarray == otherArray
, and not what you would expect.