Use of equals() method of ByteBuffer class in java.


 

Use of equals() method of ByteBuffer class in java.

In this tutorial you will see the use of equals() method of ByteBuffer class in java.

In this tutorial you will see the use of equals() method of ByteBuffer class in java.

Use of equals() method of ByteBuffer class in java.

 In this tutorial, we will check this ByteBuffer is equal to another object or not.

ByteBuffer API:

The java.nio.ByteBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ByteBuffer allocate(int capacity)  The allocate(..)method allocate a new byte buffer.
boolean equals(object obj) The equals() method tells this buffer is equals or not to another object.
abstract ByteBuffer putInt(int index, byte b) The putInt(..) method write four byte containing the given int value into associated buffer.
abstract ByteBuffer putChar(int index, byte b) The putChar(..) method write 2 byte containing the given char value into associated buffer.

code

import java.nio.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class ByteBufferEqual{
  public static final int size = 256;
  public static void main(String[] argvthrows Exception {
    byte[] bytes = new byte[size];
    ByteBuffer bytebuf1 = ByteBuffer.wrap(bytes);
    ByteBuffer bytebuf = ByteBuffer.allocate(size);
    if (bytebuf1.equals(bytebuf)) {
      System.out.println("Equals");
    else {
      System.out.println("Not equals");
    }
    bytebuf1.putInt(12);
    bytebuf.putChar('e');
    if (bytebuf1.equals(bytebuf)) {
      System.out.println("Equals");
    else {
      System.out.println("Not equals");
    }
    CharBuffer charbuf = CharBuffer.allocate(size);
    if (bytebuf1.equals(charbuf)) {
      System.out.println("Equals");
    else {
      System.out.println("Not equals");
    }
  }
}

Output

C:\w>java ByteBufferEqual
Equals
Not equals
Not equals

Download this code

Ads