Sunday 9 June 2019

nio: Buffer apis chaining


Buffer API is implemented using Builder pattern, you can chain the apis.

For example,
ByteBuffer byteBuffer = ByteBuffer.allocate(5);

byteBuffer.put(0, (byte)'H');
byteBuffer.put(1, (byte)'I');
byteBuffer.limit(2);

Above statements can be chained like below.
byteBuffer.put(0, (byte)'H').put(, (byte)'I').limit(2);

Find the below working application.

Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 public static void main(String args[]) throws Exception {
  ByteBuffer byteBuffer = ByteBuffer.allocate(5);

  byteBuffer.put(0, (byte) 'H').put(1, (byte) 'I').limit(2);

  byte[] arr = byteBuffer.array();

  System.out.println((char) arr[0] + "" + (char) arr[1]);

 }
}

Output
HI


Previous                                                 Next                                                 Home

No comments:

Post a Comment