Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

java - Creating a byte[] from a List<Byte>

What is the most efficient way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...