Let's assume I have the following:
final ByteArrayOutputStream boas = new ByteArrayOutputStream();
final byte[] sample = {1,2,3,4,5,6,7,8,9,10};
boas.write(sample);
At this point the backing array byte buf[]
within boas
contains the 10 bytes above (and 22 padding bytes).
If I call reset on boas
the count
and size
and all other factors indicate it's empty but internally byte buf[]
remains unchanged and populated.
Is there anyway to truly clear this down without creating an entirely new ByteArrayOutputStream
?
More generally, is there a reason why ByteArrayOutputStream behaves like this rather than emptying the byte[]
?
The Javadoc of ByteArrayOutputStream.reset()
states
Resets the
count
field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded. The output stream can be used again, reusing the already allocated buffer space.
Performance wise it makes sense to reuse an already allocated buffer.
If you want a different behaviour you can derive a class from ByteArrayOutputStream
and override reset()
. Both buf[]
and count
are protected members, so for instance you could clear buf
if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With