Timmmm
Timmmm

Reputation: 96556

Efficient growable java byte array that allows access to bytes

Does anyone know of a Java class to store bytes that satisfies the following conditions?

  1. Stores bytes efficiently (i.e. not one object per bytes).
  2. Grows automatically, like a StringBuilder.
  3. Allows indexed access to all of its bytes (without copying everything to a byte[].

Nothing I've found so far satisfies these. Specifically:

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

Answers (4)

user5268501
user5268501

Reputation:

There are some implementations for high performance primitive collections such as:

hppc or Koloboke

Upvotes: 1

Durandal
Durandal

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

Kayaman
Kayaman

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

Gregory Bishop
Gregory Bishop

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

Related Questions