Java varargs with 2-dimensional arrays

The question was left here because people answered it, my problem was that the version of the API that I used was not synchronized with the documents that I had ... You really can do this.

Is it possible to use a 2-dimensional array in Java as an argument to the argument that vararg arrays expects?

The function I'm trying to call is

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

and I have a 2nd byte array (byte [] [] data = blah)

however, if I try to call

 sadd(key,data); 

I get the following compiler error:

(the actual byte of the argument [] [] cannot be converted to byte [] by converting the method call)

Is it possible to use a 2-dimensional array as a vararg array type?

+4
source share
4 answers

The following works for me. Perhaps you are not doing what you think, what you think?

 @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; } 
+6
source

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

 byte[][] data = new byte[1][]; byte[] key = new byte[1]; long sadd = sadd(key, data); 
+2
source
 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 used a 2-dimensional array as a var args parameter and a 1-dimensional array as a fixed parameter. Refer to this code if this can help you! :)

+1
source

This is not possible because the compiler is not able to infer two dimensions. When using a one-dimensional array, you can define the length of the array as the number of auxiliary arguments (those that are optional).

For example: suppose a method definition includes n required parameters, and at run time you add m more arguments. Those arguments m are going to make up an array of helper arguments. Length m . In the case of a two-dimensional array, the compiler should present two dimensions for the array in such a way that: dimension1 * dimension2 = m .

0
source

All Articles