Why does this work:
String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);
but this does not:
List<String> list = Arrays.asList({"a","b","c"});
list = Arrays.asList(array); but this does not: List Why does this work: but this does not: Your question is why one works and the other does not, right? Well, the reason is that What you seem to imply with it is that you want to pass an array initializer without providing a full array creation expression (JLS 15.10). The correct array creation expressions are, as others have pointed out: As stated in JLS 10.6 Array Initializers, or As stated in JLS 15.10 Array Creation Expressions. This second one is useful for inlining, so you could pass it instead of an array variable directly. Since the Or simply pass the variable arguments that will be automatically mapped to an array:
Initialize List<> with Arrays.asList
75.7k Views
Asked by
unsafe_where_true
At
String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);
List<String> list = Arrays.asList({"a","b","c"});
There are 3 best solutions below
On
{"a","b","c"} is not a valid Java expression, and therefore the compiler cannot accept it.String[] array = {"a", "b", "c"};
String[] array = new String[]{"a", "b", "c"};
asList method in Arrays uses variable arguments, and variable arguments expressions are mapped to arrays, you could either pass an inline array as in:List<String> list = Arrays.asList(new String[]{"a", "b", "c"});
List<String> list = Arrays.asList("a","b","c");
This is a short hand only available when constructing and assigning an array.
You can do this though:
As
asListcan take "vararg" arguments.