Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize List<> with Arrays.asList [duplicate]

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"}); 
like image 708
transient_loop Avatar asked May 23 '12 20:05

transient_loop


People also ask

What does Arrays asList () do?

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.

Does array copy asList?

asList method. Using this method, we can convert from an array to a fixed-size List object. This List is just a wrapper that makes the array available as a list. No data is copied or created.


2 Answers

This is a short hand only available when constructing and assigning an array.

String[] array = {"a", "b", "c"}; 

You can do this though:

List<String> list = Arrays.asList("a","b","c"); 

As asList can take "vararg" arguments.

like image 175
Mattias Isegran Bergander Avatar answered Sep 20 '22 04:09

Mattias Isegran Bergander


Your question is why one works and the other does not, right?

Well, the reason is that {"a","b","c"} is not a valid Java expression, and therefore the compiler cannot accept it.

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:

String[] array = {"a", "b", "c"}; 

As stated in JLS 10.6 Array Initializers, or

String[] array = new String[]{"a", "b", "c"}; 

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 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"}); 

Or simply pass the variable arguments that will be automatically mapped to an array:

List<String> list = Arrays.asList("a","b","c"); 
like image 39
Edwin Dalorzo Avatar answered Sep 23 '22 04:09

Edwin Dalorzo