LongBuffer compact() method in Java
Last Updated :
19 Sep, 2018
The compact() method of java.nio.LongBuffer Class is used to compact the given buffer.
The values between the buffer’s current position and its limit are copied to the beginning of the buffer. The buffer’s position is then set to n+1 and its limit is set to its capacity. The buffer’s position is set to the number of floats copied.
Syntax:
public abstract LongBuffer compact()
Return Value: This method returns the new LongBuffer 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:
Examples 1:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 10 ;
LongBuffer ib = LongBuffer.allocate(capacity);
ib.put( 8 );
ib.put( 9 );
ib.put( 9 );
System.out.println( "Original LongBuffer: "
+ Arrays.toString(ib.array()));
System.out.println( "Position: " + ib.position());
System.out.println( "limit: " + ib.limit());
LongBuffer LongBuffer = ib.compact();
System.out.println( "\nCompacted LongBuffer: "
+ Arrays.toString(LongBuffer.array()));
System.out.println( "Position: " + LongBuffer.position());
System.out.println( "limit: " + LongBuffer.limit());
LongBuffer.put( 9 );
System.out.println( "\nUpdated Compacted LongBuffer: "
+ Arrays.toString(LongBuffer.array()));
System.out.println( "Position: " + LongBuffer.position());
System.out.println( "limit: " + LongBuffer.limit());
}
}
|
Output:
Original LongBuffer: [8, 9, 9, 0, 0, 0, 0, 0, 0, 0]
Position: 3
limit: 10
Compacted LongBuffer: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Position: 7
limit: 10
Updated Compacted LongBuffer: [0, 0, 0, 0, 0, 0, 0, 9, 0, 0]
Position: 8
limit: 10
Examples 2:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 10 ;
try {
LongBuffer ib = LongBuffer.allocate(capacity);
ib.put( 8 );
ib.put( 9 );
ib.put( 9 );
ib.rewind();
LongBuffer ib1 = ib.asReadOnlyBuffer();
System.out.print( "ReadOnlyBuffer LongBuffer: " );
while (ib1.hasRemaining())
System.out.print(ib1.get() + ", " );
System.out.println( "" );
System.out.println( "\nPosition: " + ib.position());
System.out.println( "\nlimit: " + ib.limit());
System.out.println( "\nTrying to compact the ReadOnlyBuffer ib1" );
LongBuffer LongBuffer = ib1.compact();
}
catch (IllegalArgumentException e) {
System.out.println( "Exception throws " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println( "Exception throws " + e);
}
}
}
|
Output:
ReadOnlyBuffer LongBuffer: 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
Position: 0
limit: 10
Trying to compact the ReadOnlyBuffer ib1
Exception throws java.nio.ReadOnlyBufferException
Share your thoughts in the comments
Please Login to comment...