开发者

Creating a byte[] from a List<Byte>

开发者 https://www.devze.com 2022-12-09 00:36 出处:网络
W开发者_开发技巧hat is the most efficient way to do this?byte[] byteArray = new byte[byteList.size()];

W开发者_开发技巧hat is the most efficient way to do this?


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

You may not like it but that’s about the only way to create a Genuine™ Array® of byte.

As pointed out in the comments, there are other ways. However, none of those ways gets around a) creating an array and b) assigning each element. This one uses an iterator.

byte[] byteArray = new byte[byteList.size()];
int index = 0;
for (byte b : byteList) {
    byteArray[index++] = b;
}


The toArray() method sounds like a good choice.

Update: Although, as folks have kindly pointed out, this works with "boxed" values. So a plain for-loop looks like a very good choice, too.


Using Bytes.toArray(Collection<Byte>) (from Google's Guava library.)

Example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.common.primitives.Bytes;

class Test {
    public static void main(String[] args) {
        List<Byte> byteList = new ArrayList<Byte>();
        byteList.add((byte) 1);
        byteList.add((byte) 2);
        byteList.add((byte) 3);
        byte[] byteArray = Bytes.toArray(byteList);
        System.out.println(Arrays.toString(byteArray));
    }
}

Or similarly, using PCJ:

import bak.pcj.Adapter;

// ...

byte[] byteArray = Adapter.asBytes(byteList).toArray();
0

精彩评论

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