DoubleBuffer compact() method in Java With Examples

The Java.nio.DoubleBuffer has a compact() function. To compress the supplied buffer, utilize the DoubleBuffer Class. The values are transferred to the buffer starting from the point of the buffer and its limit. Next, n+1 is assigned to the buffer's slot, and its capacity is set as its limit. The amount of replicated floats determines the position of the buffer.

Syntax:

Return Value: The new DoubleBuffer that is returned by this method has the same contents as this buffer.

Exception: The ReadOnlyBufferException is raised by this function if the buffer is read-only.

Example 1:

A buffer of double-precision floating-point integers can be handled using DoubleBuffer, a class from the java.nio package, as shown in the Java code that is given. The buffer is subsequently ready for additional writes by using the compact() method to create a compacted buffer, which moves the remaining elements to the beginning. After displaying the current condition of the compressed buffer and adding a new value, DoubleBuffer shows how to effectively handle data for further operations while preserving buffer states like position and limit.

Implementation:

FileName: BufferCompactExample1.java

Output:

 
The Original DoubleBuffer is given by : [6.320000171661377, 7.650000095367432, 8.720000267028809, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
at the position: 3
at the limit: 10
The Compacted DoubleBuffer is given by : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
at the Position: 7
at the limit: 10
The Updated Compacted DoubleBuffer is given by : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.609999656677246, 0.0, 0.0]
at the Position: 8
at the limit: 10   

Example 2:

The code shows how to use DoubleBuffer in Java. It first allows a 10-byte DoubleBuffer, inserts three floating-point integers into it, and then rewinds it. AsReadOnlyBuffer() creates a read-only clone of the buffer. The position and limit of the read-only buffer, along with its contents and status, are printed. A ReadOnlyBufferException is raised when the read-only buffer is attempted to be compacted using compact() since this operation is not permitted on read-only buffers.

Implementation:

FileName: BufferCompactExample2.java

Output:

 
The ReadOnlyBuffer DoubleBuffer is given by: 6.320000171661377, 7.650000095367432, 8.720000267028809, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, at the Position: 0
at the limit: 10
Trying to compact the doublebuff1 ReadOnlyBuffer
The Exception throws java.nio.ReadOnlyBufferException