сравнить содержимое ByteBuffer? - PullRequest
11 голосов
/ 22 сентября 2010

Какой самый простой способ в Java сравнить содержимое двух байтовых буферов для проверки на равенство?

Ответы [ 2 ]

13 голосов
/ 22 сентября 2010

Вы также можете проверить метод equals().

Указывает, равен ли этот буфер другому объекту.

Два байтовых буфераравны тогда и только тогда, когда

  1. Они имеют одинаковый тип элемента,
  2. Они имеют одинаковое количество оставшихся элементов и
  3. Две последовательности оставшихсяэлементы, рассматриваемые независимо от их начальных позиций, поточечно равны.

Байт-буфер не равен объекту любого другого типа.

2 голосов
/ 12 августа 2018

В качестве альтернативы, с 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)
...