Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good resizable, random access, efficient byte vector class in Java?

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!
  • pure RAM implementation of java.nio.channels.FileChannel. Can't find one. (Remember I don't have a file system.)
  • Apache Commons VFS and the RAM filesystem. If I must I will, but I really like something lighter weight...

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?

like image 350
David Given Avatar asked Oct 09 '22 21:10

David Given


1 Answers

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.

like image 149
Alnitak Avatar answered Oct 13 '22 09:10

Alnitak