在Java中,比较两个ByteBuffer的内容以检查是否相等的最简单方法是什么?
您还可以查看equals()
方法。
判断此缓冲区是否等于另一个对象。
仅当以下条件全部满足时,两个字节缓冲区才相等:
- 它们具有相同的元素类型,
- 它们具有相同数量的剩余元素,且
- 独立于其起始位置考虑的两个剩余元素序列在逐一比较时相等。
字节缓冲区不等于任何其他类型的对象。
.equals
方法了。我猜测OP只想比较内容。 - aioobe另外,使用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)
ByteBuffer
时不匹配的相对索引。 - Naman