执行此操作的最有效方法是什么?
发布于 2009-10-14 10:39:35
byte[] byteArray = new byte[byteList.size()];
for (int index = 0; index < byteList.size(); index++) {
byteArray[index] = byteList.get(index);
}您可能不喜欢它,但这是创建真正的byte™阵列®的唯一方法。
正如评论中指出的,还有其他方法。然而,这些方法都绕过了a)创建数组和b)分配每个元素。这个使用的是iterator。
byte[] byteArray = new byte[byteList.size()];
int index = 0;
for (byte b : byteList) {
byteArray[index++] = b;
}发布于 2009-10-14 10:34:03
toArray()方法听起来是个不错的选择。
更新:尽管,正如人们友好地指出的那样,这适用于“盒装”值。因此,普通的for-loop看起来也是一个非常好的选择。
发布于 2009-10-14 12:54:57
使用Bytes.toArray(http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/primitives/Bytes.html#toArray(java.util.Collection%29)`(Collection)` (来自谷歌的Guava库)。
示例:
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));
}
}或者类似地,使用PCJ
import bak.pcj.Adapter;
// ...
byte[] byteArray = Adapter.asBytes(byteList).toArray();https://stackoverflow.com/questions/1565483
复制相似问题