比较ByteBuffer的内容?

12

在Java中,比较两个ByteBuffer的内容以检查是否相等的最简单方法是什么?


还可以使用JDK/11中引入的API,进一步查找在比较两个 ByteBuffer 时不匹配的相对索引。 - Naman
2个回答

16

您还可以查看equals()方法。

判断此缓冲区是否等于另一个对象。

仅当以下条件全部满足时,两个字节缓冲区才相等:

  1. 它们具有相同的元素类型,
  2. 它们具有相同数量的剩余元素,且
  3. 独立于其起始位置考虑的两个剩余元素序列在逐一比较时相等。

字节缓冲区不等于任何其他类型的对象。


凭借17.7k的声望,我们可以推断他已经考虑过.equals方法了。我猜测OP只想比较内容。 - aioobe
仍然,他明确要求“比较两个ByteBuffer的内容”。 - aioobe
3
当然,我是人类,我忘记在提问前先查看Javadoc了。 呃。 :-) 我询问了检查相等性的方法,所以这是最好的方法。 - Jason S
4
注意这一点。定义中的关键短语是“剩余元素”。因此,如果两个ByteBuffer都处于写模式,并且它们的内容是通过调用各种put()方法设置的,则没有“剩余元素”,equals将始终返回true。要使equals()起作用,您需要在最后一个put()之后调用rewind()。 - RenniePet

4

另外,使用JDK/11,还有一种比较ByteBuffer的方法。主要关注两者之间不匹配的API可以使用以下方式:

int mismatchBetweenTwoBuffers = byteBuffer1.mismatch(byteBuffer2);
if(mismatchBetweenTwoBuffers == -1) {
    System.out.println("The buffers are equal!");
} else {
    System.out.println("The buffers are mismatched at - " + mismatchBetweenTwoBuffers);
}

以下是该技术的说明文档:

/**
 * Finds and returns the relative index of the first mismatch between this
 * buffer and a given buffer.  The index is relative to the
 * {@link #position() position} of each buffer and will be in the range of
 * 0 (inclusive) up to the smaller of the {@link #remaining() remaining}
 * elements in each buffer (exclusive).
 *
 * <p> If the two buffers share a common prefix then the returned index is
 * the length of the common prefix and it follows that there is a mismatch
 * between the two buffers at that index within the respective buffers.
 * If one buffer is a proper prefix of the other then the returned index is
 * the smaller of the remaining elements in each buffer, and it follows that
 * the index is only valid for the buffer with the larger number of
 * remaining elements.
 * Otherwise, there is no mismatch.
 *
 * @return  The relative index of the first mismatch between this and the
 *          given buffer, otherwise -1 if no mismatch.
 *
 * @since 11
 */
public int mismatch(ByteBuffer that)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接