如何将一个byte[]列表传递为可变参数参数?

huangapple go评论80阅读模式
英文:

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&lt;byte[]&gt; 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

这里有两个问题:

  • Bytebyte 是不同的类型。
  • 创建数组的数组的语法是错误的 - 应该是 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 and byte 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&lt;byte[]&gt; myList = new ArrayList&lt;&gt;();
        myList.add(new byte[10]);
        myList.add(new byte[5]);
        doSomething(myList.toArray(new byte[0][]));
    }

    static void doSomething(byte[]... values) {
        System.out.printf(&quot;Array contained %d values%n&quot;, values.length);
    }
}

huangapple
  • 本文由 发表于 2020年9月11日 23:49:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63850348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定