Java-Compacting

Compacting

Sometimes, you may wish to read some, but not all, of the data from a buffer, then resume filling it. To do this, the unread data elements need to be shifted down so that the first element is at index zero. While this could be inefficient if done repeatedly, it’s occasionally necessary, and the API provides a method, compact( ), to do it for you. The buffer implementation can potentially copy the data much more efficiently than you could by using the get( ) and put( ) methods. So if you have a need to do this, use compact( ). The following figure shows a buffer from which we have readed some elements and that we now want to compact.

Doing Compacting :

compacting

Results in the buffer state shown in following figure :

Several things have happened here. You can see that data elements 4-9 were copied to locations 0-5. Locations 6 to 9 were unaffected but are now at or beyond the current position and therefore are “dead.”  Note that the position has been set to the number of data elements copied. That is, the buffer is now positioned to insert following the last “live” element in the buffer. And finally, the limit has been set to the capacity so the buffer can once again be filled fully. Locations 6 to 9 can be overwritten by subsequent calls to put( ).

The effect of calling compact( ) is to drop the data elements already readed, preserve what hasn’t been readed, and make the buffer ready to resume filling to capacity. If you want to read the buffer contents after compaction, the buffer will need to be flipped. This is true whether you have subsequently added any new data elements to the buffer or not.

Program

output

Program Source

import java.nio.ByteBuffer;

public class Javaapp {

    public static void main(String[] args) {

        ByteBuffer buf = ByteBuffer.allocate(12);
        byte by[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        buf.put(by);
        buf.flip();
        
        for(int i=0;i<4;i++) 
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
        
        buf.compact();
        buf.put(new byte[]{110,115,120,125});
        buf.flip();
        
        System.out.println();
        while(buf.hasRemaining()) 
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
    }
}

Leave a Comment