java.nio.DoubleBuffer
is a class we can use to store a buffer of doubles.
We can use this class’s clear()
method to clear a buffer. Clearing a buffer means:
Capacity
is the number of elements a buffer contains. The limit
of a buffer is its first index that should not be read or written. The limit
of a buffer should be less than or equal to its capacity
.Marking
a position means recording a position that can be restored by the DoubleBuffer.reset()
method. This marked position is discarded by the DoubleBuffer.clear()
method.The DoubleBuffer.clear()
method is declared as follows:
buff.clear()
buff
: The DoubleBuffer
to be cleared.The DoubleBuffer.clear()
method returns the DoubleBuffer
buff
after cleaning it.
Consider the code snippet below, which demonstrates the use of the DoubleBuffer.clear()
method.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 4;DoubleBuffer buff1 = DoubleBuffer.allocate(n1);buff1.put(1.7);buff1.put(4.9);buff1.limit(3);buff1.mark();System.out.println("buff1: " + Arrays.toString(buff1.array()));System.out.println("position at(before clear): " + buff1.position());System.out.println("Limit at(before clear): " + buff1.limit());buff1.mark();System.out.println("clear()");buff1.clear();System.out.println("position at(after rewind): " + buff1.position());System.out.println("Limit at(before clear): " + buff1.limit());}}
DoubleBuffer
buff1
is declared in line 7 with the capacity n1 = 4
.buff1
using the put()
method in lines 8-9. After adding the first element, the position of buff1
is incremented from 0 to 1. After adding the second element, the position of buff1
is incremented from 1 to 2.buff1
before clear()
is 2. After calling the clear()
method in line 21, the position of buff1
is set to 0.buff1
is set to 3 using the limit()
method in line 11. The limit of buff1
before clear is 3. After calling the clear()
method in line 21, the limit of buff1
is set to its capacity, which is 4.buff1
is marked to 2 using the mark()
method in line 12. After calling the clear()
method in line 21, the mark of buff1
is discarded and the position is set to 0.Free Resources