比较ByteBuffer的内容?

时间:2010-09-22 13:48:52

标签: java bytebuffer

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

2 个答案:

答案 0 :(得分:13)

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

  

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

     

当且仅当

时,两个字节的缓冲区相等      
      
  1. 它们具有相同的元素类型
  2.   
  3. 它们具有相同数量的剩余元素,
  4.   
  5. 与其起始位置无关地考虑的两个剩余元素序列在点上是相等的。
  6.         

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

答案 1 :(得分: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)