简体   繁体   中英

Java: what is the best way to convert ArrayList<Byte> to byte[]?

ArrayList<Byte> bytes = new ArrayList<Byte>();
try {
    int data = putObjectRequest.getInputStream().read();
    bytes.add((byte) data);
    while (data != -1) {
        data = putObjectRequest.getInputStream().read();
        bytes.add((byte)data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

I want to convert this to byte[] . is this this the only way?

byte[] byteArray = new byte[bytes.size()];
for (int i = 0; i < bytes.size(); i++) {
   byteArray[i] = bytes.get(i);
}

I'd suggest using a ByteArrayOutputStream instead of an ArrayList<Byte> to collect your input:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
    int data = putObjectRequest.getInputStream().read();
    while (data != -1) {
        bos.write(data);
        data = putObjectRequest.getInputStream().read();
    }
} catch (IOException e) {
    e.printStackTrace();
}
byte[] byteArray = bos.toByteArray();

This avoids the horrible overhead of boxing and unboxing every byte. (I also fixed a small bug in your original code where you would write -1 if putObjectRequest was empty.)

byte[] byteArray = new byte[bytes.size()];
for (int i = 0; i < bytes.size(); i++) {
   byteArray[i] = bytes.get(i);
}

Yes, this is the only way.

byte[] byteArray = bytes.toArray(new byte[bytes.size()]);

Using toArray() as proposed in another answer does not work because the method can't automatically convert the wrapper type Byte to the primitive byte .

在Apache Commons中使用ArrayUtils

byte[] byteArray = ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()]));

Nope. Easier:

Byte[] byteArray = bytes.toArray(new Byte[bytes.size()]);

And if you really want primitives:

byte[] primitives = new byte[byteArray.length]
for (int i = 0; i < byteArray.length; i++) {
  primitives [i] = (byte)byteArray[i];
}

This guarantees you linear time complexity for both linked list and resizing array implementations.

It's been supported since 5.0:

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray(T[])

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html

You could always use something like TByteList from trove4j , instead of your ArrayList<Byte> . Your algorithm would then become:

TByteList bytes = new TByteArrayList();
try {
    int data = putObjectRequest.getInputStream().read();
    bytes.add((byte) data);
    while (data != -1) {
        data = putObjectRequest.getInputStream().read();
        bytes.add((byte)data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

byte[] byteArray = bytes.toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM