Search code examples
javaequalscharbuffer

How exactly CharBuffer equals() method works?


I cannot understand particular details of CharBuffer equals() method functioning.

I don't understand this "considered independently of their starting positions" phrase:

Two char buffers are equal if, and only if,

They have the same element type,

They have the same number of remaining elements, and

The two sequences of remaining elements, considered independently of their starting positions, are pointwise equal.

I studies these good examples - more examples, but I don't understand the idea.

Could anyone explain in different words and with minimal insightful example code?

Particularly I find this strange:

CharBuffer cb1 = CharBuffer.allocate(10);
cb1.put('a');
cb1.put('b');
//cb1.rewind();
System.out.println(cb1);


CharBuffer cb2 = CharBuffer.allocate(10);
cb2.put(4,'a');
cb2.put(5,'b');
//cb2.rewind();
System.out.println(cb2);

// false, uncommenting rewind() - also false
// but shall be true - "considered independently of starting positions" ?
System.out.println(cb1.equals(cb2));  

Solution

  • The CharBuffer are compared by what is their remaining content. It means that the equals() check starts from the current buffer position and not from the buffer start. As per Buffer.position():

    A buffer's position is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit.

    Some methods like put(char) will change the buffer position:

    CharBuffer cb1 = CharBuffer.allocate(10);
    cb1.put('a'); // increments position
    cb1.put('b'); // increments position
    
    CharBuffer cb2 = CharBuffer.allocate(8);
    
    System.out.println(cb1.equals(cb2)); // true, 00000000 equals 00000000
    

    In your example after cb1.rewind() the first buffer is ab00000000 while the second buffer is 0000ab0000. Calling cb2.rewind() is not needed as put(char, int) doesn't change the buffer position:

    CharBuffer cb1 = CharBuffer.allocate(10);
    cb1.put((char) 0);
    cb1.put((char) 0);
    cb1.put((char) 0);
    cb1.put((char) 0);
    cb1.put('a');
    cb1.put('b');
    // put(char) increments position so we need to rewind
    cb1.rewind(); 
    
    CharBuffer cb2 = CharBuffer.allocate(10);
    cb2.put(4, 'a');
    cb2.put(5, 'b');
    
    System.out.println(cb1.equals(cb2)); // true, 0000ab0000 equals 0000ab0000