Vikrant Kashyap Vikrant Kashyap - 7 months ago 16
Java Question

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

I am not new to java

Collections
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"};
obj_lStr.addAll(Arrays.asList(obj_arrStr));


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

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

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


but I Got a
Compilation Error
which was

Main.java:13: error: illegal start of expression
x.addAll(Arrays.asList({"someString", "noString", "abcString"}));
^
Main.java:13: error: ')' expected
x.addAll(Arrays.asList({"someString", "noString", "abcString"}));
^
Main.java:13: 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"));


then
compilation error
is gone.


Question :- Why is it so ? why
asList()
function raised Compilation error with
{"","",""}
but not for this
("","","")
?

Answer

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

but

int[] a new int[3];
a = {1,2,4}; // doesn't work