Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java varags method(int[] ...x) accept this "new int[1][1]" 2d array type for argument? [duplicate]

I have method like this.

void method(int[] ...x){}

and i call method using method(new int[]{1,2,3,4}); it's ok. But compiler compile this 2d array type too.

method(new int[][]{new int[]{1,2,3},new int[]{4,5,6}});

I want know the reason. method has 1d array type reference. but compiler accept 2d array type.

like image 231
Udeesha Induwara Avatar asked Nov 16 '25 19:11

Udeesha Induwara


1 Answers

The underlying type of a variadic method function(Object... args) is function(Object[] args)

So an Object... is only a syntactic sugar for an Object[].

So the method void method(int[] ...x){} in your case having 1D array as parameter should be read as void method(int[][] x){} having 2D array as parameter

Hence it compiles and will give no runtime error also.

like image 107
Ashishkumar Singh Avatar answered Nov 19 '25 10:11

Ashishkumar Singh