【问题标题】:compare ByteBuffer contents?比较 ByteBuffer 的内容?
【发布时间】:2011-04-15 18:07:32
【问题描述】:

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

【问题讨论】:

标签: java bytebuffer


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 拥有 17.7 k 的声誉,我们可以假设他已经考虑过 .equals 方法。我怀疑 OP 只想比较内容。
  • 不过,他还是明确要求“比较两个 ByteBuffer 的内容”。
  • 当然我是人,我忘了在问之前先检查javadoc。呃。 :-) 我要求检查是否相等,所以这是最好的方法。
  • 小心这个。定义中的关键词是“剩余元素”。因此,如果两个 ByteBuffers 处于写入模式,并且它们的内容已通过调用各种 put() 方法设置,则没有“剩余元素”,equals 将始终返回 true。要让 equals() 工作,您需要在最后一次 put() 之后调用 rewind()。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多