user439407
user439407

Reputation: 1756

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?

Upvotes: 4

Views: 2170

Answers (4)

Shashank Agarwal
Shashank Agarwal

Reputation: 1122

class A {
    void show(int[] ax,int[]...arr) {
        for (int is : ax) {
            System.out.println(is);
        }
        for (int[] a : arr) {
            for (int i : a) {
                System.out.println(i);
            }
        }
    }
}
public class abc{
    public static void main(String[] args) {
        A a = new A();
        int[] arr1= new int[]{10,20};
        int[][] arr2 = new int[][] { { 10, 20 }, { 20, 20 }, { 30, 20 } };
        a.show(arr1,arr2);  
    }
}

Here I have used 2-d array as var args parameter and a 1-d array as fixed parameter. Refer this code if this can help you! :)

Upvotes: 1

slim
slim

Reputation: 41271

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;
}

Upvotes: 6

Radu Stoenescu
Radu Stoenescu

Reputation: 3205

It's not possible since the compiler has no way to infer the two dimensions. When using one-dimensional array you can determine the length of the array as the number of auxiliary arguments (those that are not mandatory).

e.g: Let's say you method definition includes n mandatory parameters and, at runtime, you supply m more arguments. Those m arguments are going to make up the array of auxiliary arguments. The length is m. In case of a two-dimensional array, the compiler has to come up with two dimensions for the array such that: dimension1 * dimension2 = m.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533880

Can you provide more of your code because this compiles for me.

byte[][] data = new byte[1][];
byte[] key = new byte[1];

long sadd = sadd(key, data);

Upvotes: 2

Related Questions