ShortBuffer compact() method in Java With Examples
The compact() method of java.nio.ShortBuffer Class is used to compact the given buffer. The shorts between the buffer’s current position and its limit, if any, are copied to the beginning of the buffer. That is, the short at index p = position() is copied to index zero, the short at index p + 1 is copied to index one, and so forth until the short at index limit() – 1 is copied to index n = limit() – 1 – p. The buffer’s position is then set to n+1 and its limit is set to its capacity. The mark, if defined, is discarded. The buffer’s position is set to the number of shorts copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative put method.
public abstract ShortBuffer compact()
Return Value: This method returns the new ShortBuffer with the same content as that of this buffer.
Exception: This method throws the ReadOnlyBufferException, If this buffer is read-only.
Below program illustrates the compact() method:
Original ShortBuffer: [856, 961, 54, 0, 0, 0, 0, 0, 0, 0] Position: 3 limit: 10 Compacted ShortBuffer: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Position: 7 limit: 10 Updated Compacted ShortBuffer: [0, 0, 0, 0, 0, 0, 0, 961, 0, 0] Position: 8 limit: 10
Program 2: To demonstrate ReadOnlyBufferException.
ReadOnlyBuffer ShortBuffer: 856, 961, 6010, 0, 0, 0, 0, 0, 0, 0, Position: 0 limit: 10 Trying to compact the ReadOnlyBuffer sb1 Exception throws java.nio.ReadOnlyBufferException
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.