Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a byte[] from a List<Byte>

What is the most efficient way to do this?

like image 913
mysomic Avatar asked Oct 14 '09 10:10

mysomic


1 Answers

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;
}
like image 142
Bombe Avatar answered Sep 26 '22 00:09

Bombe