java.util.Arrays.equals() 长度有限

2022-01-24 00:00:00 arrays containers java

我需要比较两个 byte[] 数组的元素,但最多只能是固定长度.对于整个数组,我使用 java.util.Arrays.equals().当然我可以复制子范围(Arrays.copyOf()),但我不想这样做.我也确信应该有标准的方法来做到这一点,而无需新的实用方法实现.

I need to compare elements of two byte[] arrays but only up to fixed length. For whole arrays I use java.util.Arrays.equals(). Of course I can copy sub-ranges (Arrays.copyOf()) but I'd like not to do so. I am also sure there should be standard way to do so without new utility method implementation.

我正式需要的是这样的:

What I need formally is something like:

java.util.Arrays.equals(byte[] a, byte [] b, int length)

有什么众所周知的事情吗?我没有看到广泛使用的方法.

Any point to something well known? I don't see widely used approach.

再次关于防止错误答案的要求:- 数组等于长度限制.- 我有手动实现,但我想用标准的东西代替它.- 我不想要任何副本.

Again about what is asked to prevent false answers: - Array equals with limit on length. - I HAVE manual implementation but I'd like to replace it with something standard. - I don't want any copy.

提前谢谢你.

推荐答案

ByteBuffer 提供了类似于@meriton 提出的东西,但可以使用原语.这是说明性代码:

ByteBuffer provides something similar to what @meriton proposed but can work with primitives. Here is illustrative code:

import java.nio.ByteBuffer;

public class Main {

    public static void main(String [] args) throws Exception {

        byte [] a1 = {0, 1, 0, 1};
        byte [] a2 = {0, 0, 1, 0};

        boolean eq = ByteBuffer.wrap(a1,0,3).equals(ByteBuffer.wrap(a2,1,3));
        System.out.println("equal: " + eq);
    }
}

@meriton 答案的属性:

Properties of @meriton answer:

  • 结果是收集充分利用它们.
  • 其实有点抄袭(但不完整).
  • 需要引用,不能以这种方式包装原语.

这个答案特价.

  • 后端数组不会以任何方式改变.ByteBuffer.array() 返回对原始数组的引用(可能是缺点,可能是优势).
  • 它适用于原语.
  • Backend array is NOT CHANGED in any way. ByteBuffer.array() returns reference to original array (could be disadvantage, could be advantage).
  • It works with primitives.

相关文章