英文:
How to pass a List of byte[] as a varargs parameter?
问题
My question is very close to this question. But it's not the same.
I have a method that accepts varargs with a signature like
static void doSomething(byte[]... values)
And a List of byte[] that I want to send to that method.
List<byte[]> myList;
How do I convert myList
to byte[]
varargs to send to doSomething
?
I thought it would be something like
doSomething(myList.toArray(new Byte[0][]));
but that did not work - It says unexpected token at 0]))
.
Thanks in advance.
英文:
My question is very close to this question. But it's not the same.
I have a method that accepts varargs with a signature like
static void doSomething(byte[]... values)
And a List of byte[] that I want to send to that method.
List<byte[]> myList;
How do I convert myList
to byte[]
varargs to send to doSomething
?
I thought it would be something like
doSomething(myList.toArray(new Byte[][0]));
but that did not work - It says unexpected token at 0]))
.
Thanks in advance.
答案1
得分: 4
这里有两个问题:
Byte
和byte
是不同的类型。- 创建数组的数组的语法是错误的 - 应该是
new byte[0][]
。说实话,数组的数组在这方面有点让人讨厌。我当然能理解为什么你期望将[0]
放在末尾,但在这种情况下并不是这样...
在进行了这个更改之后,代码就没问题了:
import java.util.*;
public class Test {
public static void main(String[] args) {
List<byte[]> myList = new ArrayList<>();
myList.add(new byte[10]);
myList.add(new byte[5]);
doSomething(myList.toArray(new byte[0][]));
}
static void doSomething(byte[]... values) {
System.out.printf("Array contained %d values%n", values.length);
}
}
英文:
There are two problems here:
Byte
andbyte
are different types- The syntax for creating the array-of-arrays is incorrect - it should be
new byte[0][]
. Arrays of arrays are annoying in that respect, to be honest. I can certainly understand why you'd expect to put the[0]
at the end, but in this case it's just not that way...
With that change in place, it's fine:
import java.util.*;
public class Test {
public static void main(String[] args) {
List<byte[]> myList = new ArrayList<>();
myList.add(new byte[10]);
myList.add(new byte[5]);
doSomething(myList.toArray(new byte[0][]));
}
static void doSomething(byte[]... values) {
System.out.printf("Array contained %d values%n", values.length);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论