Vikrant Kashyap Vikrant Kashyap - 1 year ago 87
Java Question

Method Arrays.asList() argument is not accept a type of {"",""} but ("","") works fine Why?

I am not new to java

but I have a confusion in my mind as per i described in the Following Scenario.

In my project I am implemented a code like this...

List<String> obj_lStr= new ArrayList<String>();
String[] obj_arrStr = {"someString", "noString", "abcString"};

but during code review my
lead gives me instruction to change this code and implement it without using
Array Object

then Suddenly I Change my code with this....

obj_lStr.addAll(Arrays.asList( { "someString", "noString", "abcString" }));

but I Got a
Compilation Error
which was error: illegal start of expression
x.addAll(Arrays.asList({"someString", "noString", "abcString"}));
^ error: ')' expected
x.addAll(Arrays.asList({"someString", "noString", "abcString"}));
^ error: ';' expected
x.addAll(Arrays.asList({"someString", "noString", "abcString"}));

and I Change my line of Code to this

obj_lStr.addAll(Arrays.asList("someString", "noString", "abcString"));

compilation error
is gone.

Question :- Why is it so ? why
function raised Compilation error with
but not for this

Answer Source

the signature of asList() has the answer :public static <T> List<T> asList(T... a)

it takes a varargs , so obj_lStr.addAll(Arrays.asList("someString", "noString", "abcString")); compiles bcoz your arguments will be turned into an array.

but here obj_lStr.addAll(Arrays.asList( { "someString", "noString", "abcString" }));, you need to specify the type of the array. so you can do this : obj_lStr.addAll(Arrays.asList(new String[] { "someString", "noString", "abcString" }));.

the {} initialization syntax for arrays is available only during initilization , for ex:

int[] a ={1,2,4}; // works


int[] a new int[3];
a = {1,2,4}; // doesn't work
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download