I got a map containing n message parts as a byte array. After the last fragment found its way on the map, the message should be concatenated. I found two solutions that should meet the requirements. The first uses System.arraycopy:
public byte[] getMessageBytes() throws IOException {
byte[] bytes = new byte[0];
for (final Map.Entry<Short,byte[]> entry : myMap.entrySet()) {
byte[] entryBytes = entry.getValue();
byte[] temp = new byte[bytes.length + entryBytes.length];
System.arraycopy(bytes, 0, temp, 0, bytes.length);
System.arraycopy(entryBytes, 0, temp, bytes.length, entryBytes.length);
bytes = temp;
}
return bytes;
}
And the second uses ByteArrayOutputStream:
public byte[] getMessageBytes() throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (final Map.Entry<Short,byte[]> entry : myMap.entrySet()) {
baos.write(entry.getValue());
}
baos.flush();
return baos.toByteArray();
}
What is the best method that can be seen from the angle of performance and memory usage? Is there an alternative way to perform concatenation that is even better?
source
share