0

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.

praty
  • 914
  • 9
  • 11
  • 1
    "but that did not work" - so what happened? – Jon Skeet Sep 11 '20 at 15:51
  • It says "unexpected token" at 0])) so I'm guessing it is syntactically incorrect. – praty Sep 11 '20 at 15:54
  • try `doSomething(myList.toArray(new byte[0]));` (you have one bracket pair/dimension too much) – xerx593 Sep 11 '20 at 16:08
  • no, the varargs that is expected is already an array. See, `doSomething(byte[]... values)` – praty Sep 11 '20 at 16:17
  • 1
    Right, please edit the error message into your question. *Always* include the error in a question - otherwise it's like going to the doctor and saying "I think I'm ill" and expecting a diagnosis without providing any more information. – Jon Skeet Sep 11 '20 at 16:37

1 Answers1

4

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<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);
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194