java 从 List<Byte> 创建一个 byte[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1565483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:06:56  来源:igfitidea点击:

Creating a byte[] from a List<Byte>

javaarrayslistbyte

提问by mysomic

What is the most efficient way to do this?

执行此操作的最有效方法是什么?

回答by Bombe

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.

您可能不喜欢它,但这是创建正版的唯一方法?大批?的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.

正如评论中所指出的,还有其他方法。但是,这些方法都没有绕过 a) 创建数组和 b) 分配每个元素。这个使用迭代器

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

回答by unwind

The toArray()method sounds like a good choice.

toArray()方法听起来是个不错的选择。

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.

更新:虽然,正如人们所指出的,这适用于“盒装”值。所以一个普通的for循环看起来也是一个非常好的选择。

回答by finnw

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

使用(来自 Google 的Guava库。)Bytes.toArray(Collection<Byte>)

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:

或者类似地,使用PCJ

import bak.pcj.Adapter;

// ...

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