IntBuffer equals() method in Java

Java 8Object Oriented ProgrammingProgramming

<p>The equality of two buffers can be checked using the method equals() in the class java.nio.IntBuffer. Two buffers are equal if they have the same type of elements, the same number of elements and same sequence of elements. The method equals() returns true if the buffers are equal and false otherwise.</p><p>A program that demonstrates this is given as follows &minus;</p><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">import java.nio.*; import java.util.*; public class Demo { &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; int n = 5; &nbsp; &nbsp; &nbsp; try { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IntBuffer buffer1 = IntBuffer.allocate(n); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer1.put(8); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer1.put(1); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer1.put(3); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer1.put(7); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer1.put(5); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer1.rewind(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;The first IntBuffer is: &quot; + Arrays.toString(buffer1.array())); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IntBuffer buffer2 = IntBuffer.allocate(n); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer2.put(8); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer2.put(1); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer2.put(3); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer2.put(7); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer2.put(5); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;buffer2.rewind(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;The second IntBuffer is: &quot; + Arrays.toString(buffer2.array())); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;boolean flag = buffer1.equals(buffer2); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (flag) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(&quot; Both the buffers are equal&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(&quot; Both the buffers are not equal&quot;); &nbsp; &nbsp; &nbsp; } catch (IllegalArgumentException e) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;Error!!! IllegalArgumentException&quot;); &nbsp; &nbsp; &nbsp; } catch (ReadOnlyBufferException e) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;Error!!! ReadOnlyBufferException&quot;); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><p>The output of the above program is as follows &minus;</p><h2>Output</h2><pre class="result notranslate">The first IntBuffer is: [8, 1, 3, 7, 5] The second IntBuffer is: [8, 1, 3, 7, 5] Both the buffers are equal</pre>
Updated on 30-Jul-2019 22:30:25