Share on Google+Share on Google+

Create a short array with the help of short buffer.

Advertisement
In this tutorial, you will see how to create a short array with the help of short buffer.

Create a short array with the help of short buffer.

 In this tutorial, we will see how to create a short array with the help of short buffer.

ShortBuffer API:

The java.nio.ShortBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ShortBuffer allocate( int capacity)  The allocate(..) method allocate a short buffer of given capacity. 
short[] array() The array() method returns short array based on short buffer.
abstract short get() The get() method read short value from current position and increment position..

Code

import java.nio.*;
import java.nio.ShortBuffer;

public class ShortBuffArray {
  public static void main(String[] arg) {
    ShortBuffer shortBuff = ShortBuffer.allocate(1024);
    shortBuff.put((short43);
    shortBuff.put((short44);
    shortBuff.put((short45);
    shortBuff.flip();
    System.out
    .println("Capacity of short buffer : " 
                            
+ shortBuff.capacity());
    System.out.println("Content in shortbuffer : ");
    while (shortBuff.hasRemaining()) {
      System.out.println(shortBuff.get() " ");
    }
    short[] shortArray = shortBuff.array();
    int len = shortArray.length;
    System.out.println();
  System.out.println("Length of short buffer array : "
                                              
+ len);
System.out.println("Content in short buffer array : ");
    for (int i = 0; i < shortBuff.limit(); i++) {
      System.out.println(shortArray[i" ");
    }
  }
}

Output

C:\>java ShortBuffArray
Capacity of short buffer : 1024
Content in shortbuffer :
 43
 44
 45
Length of short buffer array : 1024
Content in short buffer array :
 43
44
45

Download this code

Advertisements

Advertisement

Posted on: August 11, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.