gpt4 book ai didi

java - 我可以使用 addAll Collection 方法添加所有元素(类型 :byte) from arrays(byte[]) to a List of type Byte?

转载 作者:搜寻专家 更新时间:2023-11-01 02:41:47 27 4
gpt4 key购买 nike

我必须附加(可变数量的)字节数组。集合似乎只适用于包装类,即 Byte。大约 20 小时后,我想到了这个,并且它有效,但我想知道它是否可以改进(添加到列表,但欢迎任何其他改进建议:),即

Collections.addAll method all the array elements to the specified collection. This is how Collections.addAll method is being called. It does the same as Arrays.asList method however it is much faster than it so performance wise this is a best way to get the array converted to ArrayList.

这是它当前的测试版

public static byte[] joinArrays(byte[]... args) {

List<Byte> arrayList = new ArrayList();

for (byte[] arg : args) { // For all array arguments...
for (int i = 0; i < arg.length; i++) { // For all elements in array
arrayList.add(Byte.valueOf(arg[i])); // ADD TO LIST
}
}
byte[] returnArray = new byte[arrayList.size()];

for (int i = 0; i < arrayList.size(); i++) {
returnArray[i] = arrayList.get(i).byteValue(); //Get byte from Byte List
}
return returnArray;
}

最佳答案

你可以坚持你的数组并避免装箱/拆箱到 Byte 中,像这样:

public static byte[] joinArrays(byte[]... args) {
int byteCount = 0;
for (byte[] arg : args) { // For all array arguments...
byteCount += arg.length;
}
byte[] returnArray = new byte[byteCount];
int offset = 0;
for (byte[] arg : args) { // For all array arguments...
System.arraycopy(arg, 0, returnArray, offset, arg.length);
offset += arg.length;
}
return returnArray;
}

关于java - 我可以使用 addAll Collection 方法添加所有元素(类型 :byte) from arrays(byte[]) to a List of type Byte?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31632026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com