Reputation: 96556
Does anyone know of a Java class to store bytes that satisfies the following conditions?
StringBuilder
.byte[]
.Nothing I've found so far satisfies these. Specifically:
byte[] : Doesn't satisfy 2.
ByteBuffer : Doesn't satisfy 2.
ByteArrayOutputStream : Doesn't satisfy 3.
ArrayList : Doesn't satisfy 1 (AFAIK, unless there's some special-case optimisation).
If I can efficiently remove bytes from the beginning of the array that would be nice. If I were writing it from scratch I would implement it as something like
{ ArrayList<byte[256]> data; int startOffset; int size; }
and then the obvious functions. Does something like this exist?
Upvotes: 1
Views: 565
Reputation:
There are some implementations for high performance primitive collections such as:
Upvotes: 1
Reputation: 20059
The laziest method will be ArrayList. Its not as inefficient as you seem to believe, since Byte instances can and will be shared, meaning there will be only 256 byte objects in the entire VM unless you yourself do a "new Byte()" somewhere.
Upvotes: 0
Reputation: 73538
Most straightforward would be to subclass ByteArrayOutputStream
and add functionality to access the underlying byte[]
.
Removal of bytes from the beginning can be implemented in different ways depending on your requirements. If you need to remove a chunk, System.arrayCopy
should work fine, if you need to remove single bytes I would put a headIndex
which would keep track of the beginning of the data (performing an arraycopy
after enough data is "removed").
Upvotes: 2
Reputation: 2017
You'd have to write one. Off the top of my head what I would do is create an ArrayList internally and store the bytes 4 to each int, with appropriate functions for masking off the bytes. Performance will be sub optimal for removing and adding individual bytes. However it will store the object in the minimal size if that is a real consideration, wasting no more than 3 bytes for storage (on top of the overhead for the ArrayList).
Upvotes: 0