Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java varargs with 2-dimensional arrays

Question is left here because people answered it, my problem was that the version of the API I was using was out of sync with the docs I had....You can in fact do this.

Is there any way to use a 2-d array in Java as an argument for an argument that expects a vararg of arrays?

The function I am trying to call is

public Long sadd(final byte[] key, final byte[]... members) {

and I have a 2-d array of bytes(byte [][] data=blah)

however if I try to call

sadd(key,data);

I get the following compiler error:

(actual argument byte[][] cannot be converted to byte[] by method invocation conversion)

Is there any way to use a 2-d array as a vararg of an array type?

like image 746
user439407 Avatar asked Jan 15 '23 16:01

user439407


1 Answers

The following works for me. Perhaps you're not doing what you think you're doing?

@Test
public void test_varargs() {
   byte[] x = new byte[] { 1, 2, 3};
   byte[] y = new byte[] { 0, 1, 2};
   assertEquals(9L, sum(x,y));
   byte[][] z = new byte[][] { x,y };
   assertEquals(9L, sum(z));
}

public long sum(final byte[]... members) {
   long sum = 0;
   for (byte[] member : members) {
       for (byte x : member) {
         sum += x;
      }
   }
   return sum;
}
like image 102
slim Avatar answered Jan 25 '23 20:01

slim