Java 中比较两个 ByteBuffer 的内容以检查是否相等的最简单方法是什么?
问问题
8546 次
2 回答
14
你也可以检查equals()
方法。
判断此缓冲区是否等于另一个对象。
当且仅当,两个字节缓冲区相等
- 它们具有相同的元素类型,
- 它们具有相同数量的剩余元素,并且
- 剩余元素的两个序列,独立于它们的起始位置考虑,是逐点相等的。
字节缓冲区不等于任何其他类型的对象。
于 2010-09-22T13:53:13.200 回答
3
或者,使用JDK/11,还有另一种将 aByteBuffer
与另一个进行比较的方法。主要专注于查找两者之间不匹配的 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)
于 2018-08-12T18:23:36.337 回答