开发者

compare ByteBuffer contents?

开发者 https://www.devze.com 2023-01-17 07:55 出处:网络
What\'s the easiest way in Java to compare the c开发者_Python百科ontents of two ByteBuffers to check for equality?You could check the equals() method too.

What's the easiest way in Java to compare the c开发者_Python百科ontents of two ByteBuffers to check for equality?


You could check the equals() method too.

Tells whether or not this buffer is equal to another object.

Two byte buffers are equal if, and only if,

  1. They have the same element type,
  2. They have the same number of remaining elements, and
  3. The two sequences of remaining elements, considered independently of their starting positions, are pointwise equal.

A byte buffer is not equal to any other type of object.


Alternatively, with JDK/11, there is another way of comparing a ByteBuffer with another. The API which primarily focusses on finding the mismatch between the two can be used as -

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);
}

Its documentation reads as:-

/**
 * 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消