Java Reference
In-Depth Information
sequence of elements of a given type, and you can create buffers to hold any primitive data type except for
type
boolean
. Thus, you create different types of buffers to store
byte
values,
char
values,
short
values,
int
values,
long
values,
float
values, or
double
values. The classes in
Table 10-4
in the
java.nio
pack-
age define these buffers.
TABLE 10-4
:
Classes for Buffers
CLASS DESCRIPTION
ByteBuffer
A buffer that stores values of type
byte
. You can also store the binary values of any of the other primit-
ive types in this buffer, except for type
boolean
. Each binary value that you store occupies a number of
bytes in the buffer determined by the type — values of type
char
or
short
occupy 2 bytes,
int
values
occupy 4 bytes, and so on.
CharBuffer
A buffer that stores only values of type
char
.
ShortBuffer
A buffer that stores only values of type
short
.
IntBuffer
A buffer that stores only values of type
int
.
LongBuffer
A buffer that stores only values of type
long
.
FloatBuffer
A buffer that stores only values of type
float
.
DoubleBuffer
A buffer that stores only values of type
double
.
I keep repeating “except for type
boolean
” every so often, so I better address that. There is no buffer type
that provides for type
boolean
values, but, of course, you may actually want to record some
boolean
values
in a file. In this case, you have to devise a suitable alternative representation. You could use integer values
0 and 1, or perhaps strings
"true"
and
"false"
, or even characters
't'
and
'f'
. You could even represent
each
boolean
value as a single bit and pack eight of them at a time into a single byte, but this is likely to be
worthwhile only if you have a lot of them. Which approach you choose depends on what is most convenient
in the context in which you are using the
boolean
values.
Although you have seven different classes defining buffers, you use only buffers of type
ByteBuffer
to
read or write data. The other types of buffers in the table above are called
view buffers
, because they are
usually created as views of an existing buffer of type
ByteBuffer
. The view buffers provide an easy way to
get data items of various types into or out of a
ByteBuffer
. You see how a little later in this chapter.
Buffer Capacity
The capacity of a buffer is the maximum number of values it can contain, not the number of bytes — unless,
of course, it stores elements of type
byte
. The capacity of a buffer is fixed when you create it and cannot
be changed subsequently. You can obtain the capacity for a buffer object as a value of type
int
by calling
the
capacity()
method that it inherits from the
Buffer
class.
Figure 10-1
shows the capacities of different
buffers when each occupies the same amount of memory.