Java-Comparing Elements

Comparing Elements

It’s occasionally necessary to compare the data contained in one buffer with that in another buffer. All buffers provide a custom equals( ) method for testing the equality of two buffers. The following example shows you how to compare the byte buffers buf1 and buf2 for equality :

The equals() contract for ByteBuffer states that two byte buffers are equal if and only if they have the same element type; they have the same number of remaining elements(from position to limit); and the two sequences of remaining elements, considered independently of their starting positions, are individually equal. This contract is the same for the other Buffer subclasses.



Program Source

import java.nio.ByteBuffer;

public class Javaapp {

    public static void main(String[] args) {

        ByteBuffer buf1 = ByteBuffer.allocate(12);
        buf1.put(new byte[]{10,20,30,40,50,60,70,80,90,100});
        ByteBuffer buf2 = ByteBuffer.allocate(12);
        buf2.put(new byte[]{60,70,80,90,100});
            System.out.println("Both buffers remaining elements are same.");

Leave a Comment