问题 比较ByteBuffer的内容?


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


6259
2017-09-22 13:48


起源

人们也可以使用 JDK / 11中引入的API,在比较两者时,另外找出不匹配的相对指数 ByteBuffer秒。 - nullpointer


答案:


你可以检查一下 equals() 方法也是。

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

两个字节的缓冲区是相等的,当且仅当

  1. 它们具有相同的元素类型,
  2. 它们具有相同数量的剩余元素,并且
  3. 与其起始位置无关地考虑的两个剩余元素序列是逐点相等的。

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


13
2017-09-22 13:53



凭借17.7 k的声誉,我们可以假设他已经考虑过了 .equals 方法。我怀疑OP只想比较内容。 - aioobe
@aioobe,他可能是Jon Skeet,每个人都是人类;) - Colin Hebert
不过,他明确要求“比较两个ByteBuffers的内容”。 - aioobe
当然我是人,我忘了在问之前先检查一下javadoc。咄。 :-)我要求检查是否相等,所以这是最好的方法。 - Jason S
小心这个。定义中的关键短语是“剩余元素”。因此,如果两个ByteBuffers处于写入模式,其内容已通过调用各种put()方法设置,则没有“剩余元素”,并且equals将始终返回true。要使equals()工作,您需要在最后一次put()之后进行一次rewind()调用。 - RenniePet


或者,用 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)

2
2017-08-12 18:23