I am trying to "clean up" a ByteBuffer
to be all zero bytes (all 0x00
). I tried to loop over all positions in the buffer and set them to 0x00
, but the efficiency is bad. Is there any better way to quickly clear a ByteBuffer
- similar to what BitSet.clear()
does?
Please note that ByteBuffer.clear()
is not an appropriate solution for me in this scenario--I have to erase all the data inside of the buffer, and not just reset the pointer to the beginning.
Any hints?
Edit: the ByteBuffer is used as a part of the hash table, and it maintains the references of the hash table entries. Every time when the hash table needs to be flushed, I have to reset the hash table entries for later hash table insertion. Since the hash table is accessed in a random-fashion, I cannot simply clear() the state of the byte buffer.
Have you tried using one of the ByteBuffer.put(byte[])
or ByteBuffer.put(ByteBuffer)
methods to write multiple zeros in one go? You could then iterate over the buffer in chunks of 100 or 1000 bytes, or whatever, using an array or buffer pre-filled with zeros.
Downside: this is an optional operation, so not all implementations of ByteBuffer are required to provide it...