5.7. Using a Buffer
Problem
You need a data structure that can act as a temporary staging area, i.e., a buffer.
Solution
Use Buffer
from Jakarta Commons Collections. A
buffer is an object that is defined by the
algorithm used for element removal. Buffer
objects
can be priority queues, staging areas, message queues, or buffers for
I/O. One of the simplest Buffer
implementations is
the UnboundedFifoBuffer
, a first-in, first-out
data structure with no size limit. The following example demonstrates
the use of an UnboundedFifoBuffer
:
import org.apache.commons.collections.Buffer; import org.apache.commons.collections.buffer.UnboundedFifoBuffer; // Create an Unbounded FIFO Buffer buffer = new UnboundedFifoBuffer( ); // Add elements to the Buffer buffer.add("A"); buffer.add("B"); buffer.add("D"); // Remove element from the buffer String value = (String) buffer.remove( ); buffer.add("E"); value = (String) buffer.remove( );
This example creates an UnboundedFifoBuffer
,
adding three elements: “A,”
“B,” and
“D.” When remove()
is invoked, the buffer selects the item that was placed
into the buffer first—the first-in is the first-out. The first
call to remove( )
returns
“A,” and the second call returns
“B.”
Discussion
A FIFO buffer can be viewed as a kind of stack; instead of
pop( )
returning the last item to be placed on the
stack, remove( )
returns the bottom of the
stack—the first item added to the Buffer
. A
Buffer
throws a
BufferUnderflowException
if you try to
remove( )
or get( )
an element ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.