The get()
methods of the DoubleBuffer
class in Java return either the value at the current buffer position or the value at a specific position in a DoubleBuffer
object, based on the parameters passed to the function.
The process is illustrated below:
To use the get()
methods, you will need to import the DoubleBuffer
class into your program, as shown below:
import java.nio.DoubleBuffer
There are variations of the get()
method:
get()
method has no parameters and returns the value of the current buffer position. The current buffer position is also incremented. The prototype of this method is shown below:public double get();
get()
method has a single parameter that represents a buffer index and returns the value of the buffer at this index. The prototype of this method is shown below:public double get(int index);
The get()
methods return a double value.
If no parameters are passed to the get()
method, it returns the current buffer position value. If the current buffer position exceeds the length of the buffer, the get()
method throws a BufferUnderflowException
.
If a buffer index is passed as a parameter to the get()
method, it returns the value stored at the specified index. If the specified index is not a valid buffer position, the get()
method throws an IndexOutOfBoundsException
.
The code below shows how the get()
methods can be used in Java:
import java.nio.*; import java.util.*; class getMethods { public static void main(String[] args) { // initialize buffer instance DoubleBuffer newBuffer = DoubleBuffer.allocate(3); // add values to buffer newBuffer.put(0.5D); newBuffer.put(2.2D); newBuffer.put(6.4D); newBuffer.rewind(); // Print buffer System.out.println("The DoubleBuffer is: " + Arrays.toString(newBuffer.array())); // Using get() to return all buffer values System.out.println("\nUsing get() to return buffer values:"); for(int i = 0; i < 3; i++) { double current_val = newBuffer.get(); System.out.println(current_val); } // Use get(int index) to find value at position 1 System.out.println("\nThe value at buffer index 1 is: "); System.out.println(newBuffer.get(1)); } }
First, a DoubleBuffer
object called newBuffer
is initialized through the allocate()
method.
Since newBuffer
has the capacity to store elements, the put()
method is invoked thrice to add values to the buffer. The rewind()
function in line sets the current buffer position to the start of the buffer, i.e., index .
Next, a for-loop
is used to extract each value stored in the buffer. Each loop iteration invokes the get()
method in line , which returns the value at the current buffer position and increments the current buffer position by .
Finally, the get()
method is invoked with a specified buffer index in line . The get()
method returns the value of the buffer at index , i.e., .
RELATED TAGS
CONTRIBUTOR
View all Courses