开发者

Flatten Ragged LinkedHashMap

I have a LinkedHashMap where CommonEnum represents a type of byte[] that开发者_如何转开发 I want to keep track of.

LinkedHashMap<CommonEnum, byte[]> map = new LinkedHashMap<CommonEnum, byte[]>();

What is the most efficient way in Java to flatten this into a continuous

byte[]

with the same ordering (thats why the HashMap is Linked).


If you can use a LinkedHashMap<CommonEnum, byte[]>, it gets easier, and I have no idea why you would use Byte[], so I assume this.

I'm not sure about most efficient, but these two would be what I think about:

    1. create a byte[] large enough (either estimate it or calculate by adding the sizes)
    2. loop through the values, using System.arraycopy for each.
    3. If the array was to long, use Arrays.copyOf to shorten it.
    1. Create a ByteArrayOutputStream
    2. loop through the values, write each byte[] to the stream.
    3. get the array.

By the way, if your CommonEnum values are always of the same order (and you can use this order as the order in the enum definition), you can use an EnumMap instead.


I'm a fan of ByteArrayOutputStream -- you could iterate through the entries in the map, and for each Byte[] value, iterate through the members, write()ing them to the stream. Then call toByteArray() at the end to get the flat version.


Depending on the number of elements and the size, the fastest way might be to first calculate the total length, create a new byte array, and copy the values using System.arraycopy. However, using ByteArrayOutputStream is also good.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜