Java Reference
In-Depth Information
Marking and Resetting
Like input streams, buffers can be marked and reset if you want to reread some data.
Unlike input streams, this can be done to all buffers, not just some of them. For a change,
the relevant methods are declared once in the
Buffer
superclass and inherited by all
the various subclasses:
public
final
Buffer
mark
()
public
final
Buffer
reset
()
The
reset()
method throws an
InvalidMarkException
, a runtime exception, if the
mark is not set. The mark is also unset when the position is set to a point before the
mark.
Object Methods
The buffer classes all provide the usual
equals()
,
hashCode()
, and
toString()
meth‐
ods. They also implement
Comparable
, and therefore provide
compareTo()
methods.
However, buffers are not
Serializable
or
Cloneable
.
Two buffers are considered to be equal if:
• They have the same type (e.g., a
ByteBuffer
is never equal to an
IntBuffer
but
may be equal to another
ByteBuffer
).
• They have the same number of elements remaining in the buffer.
• The remaining elements at the same relative positions are equal to each other.
Note that equality does not consider the buffers' elements that precede the position, the
buffers' capacity, limits, or marks. For example, this code fragment prints true even
though the first buffer is twice the size of the second:
CharBuffer
buffer1
=
CharBuffer
.
wrap
(
"12345678"
);
CharBuffer
buffer2
=
CharBuffer
.
wrap
(
"5678"
);
buffer1
.
get
();
buffer1
.
get
();
buffer1
.
get
();
buffer1
.
get
();
System
.
out
.
println
(
buffer1
.
equals
(
buffer2
));
The
hashCode()
method is implemented in accordance with the contract for equality.
That is, two equal buffers will have equal hash codes and two unequal buffers are very
unlikely to have equal hash codes. However, because the buffer's hash code changes
every time an element is added to or removed from the buffer, buffers do not make good
hash table keys.
Comparison is implemented by comparing the remaining elements in each buffer, one
by one. If all the corresponding elements are equal, the buffers are equal. Otherwise,