How to make a variational method, take one array as the first value of the varargs array?

Given the variables:

Object[] ab = new Object[] { "a", "b" }; Object[] cd = new Object[] { "c", "d" }; 

When calling the following method:

 public static void m(Object... objects) { System.out.println(Arrays.asList(objects)); } 

Using:

 m(ab, cd); 

I get the expected result:

 [[Ljava.lang.Object;@3e25a5, [Ljava.lang.Object;@19821f] 

But when using:

 m(ab); 

I get:

 [a, b] 

Since strings <- ab and not strings[0] <- ab .

How to make the compiler take the array ab as the first value of the strings array, and then get the output:

 [Ljava.lang.Object;@3e25a5 

?

+6
source share
2 answers

Typecast is on transfer, and you get what you want -

 m((Object)ab); 
+9
source

Apart from the proposed @Sudhansu. You can define variables as shown below, so you don’t have to worry about casting a method when calling a single array.

 Object ab = new Object[] { "a", "b" }; Object cd = new Object[] { "c", "d" }; 
+3
source

All Articles