Java 比较ByteBuffer内容?

Java 比较ByteBuffer内容?,java,bytebuffer,Java,Bytebuffer,Java中比较两个ByteBuffer的内容以检查相等性的最简单方法是什么?您也可以检查该方法 说明此缓冲区是否等于另一个对象 当且仅当: 它们具有相同的元素类型 它们具有相同数量的剩余元素,并且 剩余元素的两个序列独立于它们的起始位置,在点方向上相等 字节缓冲区不等于任何其他类型的对象 或者,使用,还有另一种方法将字节缓冲区与另一个字节缓冲区进行比较。API主要侧重于发现两者之间的不匹配,可用作- int mismatchBetweenTwoBuffers = byteBuffer1.mism

Java中比较两个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)
    
    /**
    *查找并返回此字段之间第一个不匹配项的相对索引
    *缓冲区和给定的缓冲区。该索引是相对于
    *每个缓冲区的{@link#position()position},并将在
    *0(包括)到{@link#remaining()remaining}中的较小者
    *每个缓冲区中的元素(独占)。
    *
    *如果两个缓冲区共享一个公共前缀,则返回的索引为
    *公共前缀的长度,因此存在不匹配
    *在相应缓冲区内该索引处的两个缓冲区之间。
    *如果一个缓冲区是另一个缓冲区的正确前缀,则返回的索引为
    *每个缓冲区中剩余元素中较小的一个,如下所示
    *该索引仅对具有较大数量的缓冲区有效
    *其余要素。
    *否则,就不存在不匹配。
    *
    *@return此值与当前值之间第一个不匹配的相对索引
    *给定缓冲区,如果没有不匹配,则为-1。
    *
    *@自11日起
    */
    公共整数不匹配(ByteBuffer that)
    
    拥有17.7K的声誉,我们可以假设他考虑了
    .equals
    方法。我怀疑OP只想比较内容。尽管如此,他还是明确要求“比较两个ByteBuffers的内容”。当然,我是人类,我忘了在询问之前先检查javadoc。Duh.:-)我要求检查是否相等,所以这是最好的方法。注意这个。定义中的关键短语是“剩余要素”。因此,如果这两个ByteBuffer处于写入模式,并且它们的内容是通过调用各种put()方法来设置的,那么就没有“剩余元素”,equals将始终返回true。要使equals()工作,您需要在最后一次put()之后进行rewind()调用。还可以使用,在比较两个
    ByteBuffer
    s时,另外找出不匹配的相对索引。