Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a variatic method take a single 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 output:

[[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 can I force the compiler to take the ab array as the first value of the strings array, and then having the output:

[Ljava.lang.Object;@3e25a5

?

like image 813
sp00m Avatar asked Mar 19 '13 09:03

sp00m


2 Answers

Typecast it while passing and you will get what you want -

m((Object)ab);
like image 89
Sudhanshu Umalkar Avatar answered Nov 15 '22 00:11

Sudhanshu Umalkar


Apart from as suggested by @Sudhansu. You can define the variables as below so you don't have to bother with casting in method call when passing single array.

Object ab = new Object[] { "a", "b" };
Object cd = new Object[] { "c", "d" };
like image 43
Abdullah Shaikh Avatar answered Nov 14 '22 23:11

Abdullah Shaikh