I'm trying to find a class for storing a vector of bytes in Java, which supports: random access (so I can get or set a byte anywhere), resizing (so I can either append stuff to the end or else manually change the size), reasonable efficiency (I might be storing megabytes of data in these things), all in memory (I don't have a file system). Any suggestions?
So far the candidates are:
byte[]
. Not resizable.java.util.Vector<Byte>
. Evil. Also painfully inefficient.java.io.ByteArrayOutputStream
. Not random-access.java.nio.ByteBuffer
. Not resizable.org.apache.commons.collections.primitives.ArrayByteList
. Not resizable. Which is weird, because it'll automatically resize if you add stuff to it, you just can't change the size explicitly!java.nio.channels.FileChannel
. Can't find one. (Remember I don't have a file system.)This seems like such an odd omission that I'm sure I must have missed something somewhere. I just figure out what. What am I missing?
I would consider a class that wraps lots of chunks of byte[]
arrays as elements of an ArrayList
or Vector
.
Make each chunk a multiple of e.g. 1024 bytes, so you accessor functions can take index >> 10
to access the right element of the ArrayList
, and then index & 0x3ff
to access the specific byte element of that array.
This will avoid the wastage of treating each byte
as a Byte
object, at the expensive of wastage of whatever's left over at the end of the last chunk.
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