The equals()
method of the IntBuffer
class in Java checks if an IntBuffer
object is equal to another object.
For the equals()
method to consider two objects as being equal, the following conditions must be satisfied:
The process is illustrated below:
Note: An
IntBuffer
object can only be considered equal to anotherIntBuffer
object, not any other type.
To use the equals()
method, you will need to import the IntBuffer
class into your program, as shown below:
import java.nio.IntBuffer
The prototype of the equals()
method is shown below:
public boolean equals(Object ob)
The equals()
method takes a single mandatory parameter, i.e., the object to compare with the buffer.
If the object is equal to the IntBuffer
, then the equals()
method returns true
; otherwise, it returns false
.
The code below shows how the equals()
method can be used in Java:
import java.nio.*;import java.util.*;class equalsMethod {public static void main(String[] args) {// initialize IntBuffer instanceIntBuffer bufferOne = IntBuffer.allocate(3);IntBuffer bufferTwo = IntBuffer.allocate(3);IntBuffer bufferThree = IntBuffer.allocate(3);DoubleBuffer bufferFour = DoubleBuffer.allocate(3);int values[] = {2, 1, 6};// add values to bufferfor(int i = 0; i < 3; i++){bufferOne.put(values[i]);bufferTwo.put(values[i]);bufferFour.put(values[i]);}bufferThree.put(2);bufferThree.put(1);// Print buffersSystem.out.println("BufferOne is: " + Arrays.toString(bufferOne.array()));System.out.println("BufferTwo is: " + Arrays.toString(bufferTwo.array()));System.out.println("BufferThree is: " + Arrays.toString(bufferThree.array()));System.out.println("BufferFour is: " + Arrays.toString(bufferFour.array()));// Compare buffersif(bufferOne.equals(bufferTwo)){System.out.println("\nBufferOne and BufferTwo are equal.");}else{System.out.println("\nBufferOne and BufferTwo are not equal.");}if(bufferOne.equals(bufferThree)){System.out.println("BufferOne and BufferThree are equal.");}else{System.out.println("BufferOne and BufferThree are not equal.");}if(bufferOne.equals(bufferFour)){System.out.println("BufferOne and BufferFour are equal.");}else{System.out.println("BufferOne and BufferFour are not equal.");}}}
First, multiple IntBuffer
objects and a DoubleBuffer
object are initialized through the allocate()
method. Each buffer has the capacity to store elements.
Next, a for-loop
adds values to the buffers through the put()
method.
The objects bufferOne
and bufferTwo
are identical in terms of their element types, the number of elements, and the sequence of elements. Therefore, the equals()
method in line returns true
.
On the other hand, bufferOne
and bufferThree
have a different sequence of elements, as the last element of both objects is different. Consequently, the equals()
method in line returns false
.
Finally, although bufferOne
and bufferFour
have the same sequence and number of values, the types of the elements differ, as bufferFour
is a DoubleBuffer
. Therefore, the equals()
method in line returns false
.