Monday 10 June 2019

NIO: check whether buffer is backed by array or not


Buffer class provides 'hasArray' method to check whether this buffer is backed up by an array or not.

Test.java

package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

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

  boolean isBuffer1BackedByArray = byteBuffer1.hasArray();
  boolean isBuffer2BackedByArray = byteBuffer2.hasArray();

  System.out.println("Is byteBuffer1 backed up by array : " + isBuffer1BackedByArray);
  System.out.println("Is byteBuffer2 backed up by array : " + isBuffer2BackedByArray);

 }
}

Output
Is byteBuffer1 backed up by array : true
Is byteBuffer2 backed up by array : false

Previous                                                 Next                                                 Home

No comments:

Post a Comment