Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a better alternative to List<T> initalization than invoking Arrays.asList?

Tags:

java

Is there a better alternative to using Arrays.asList as a List bulk initializer? Of concern is that this one is verbose and involves an extraneous class and method.

List<Double> myList = new ArrayList<Double>(Arrays.asList(3.01d, 4.02d, 5.03d));

Edit: This question pertains to a bulk initialization which would usually have more than the three values shown in the example.

like image 708
H2ONaCl Avatar asked Jul 30 '11 05:07

H2ONaCl


People also ask

Is arrays asList same as ArrayList?

asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn't implement the add and remove methods.

How is arrays asList () different than the standard way of initialising list *?

How is Arrays. asList() different than the standard way of initialising List? Explanation: List returned by Arrays. asList() is a fixed length list which doesn't allow us to add or remove element from it.

Can you modify the Collection return by arrays asList ()?

Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it.

What type of list does arrays asList return?

asList returns a fixed-size list that is​ backed by the specified array; the returned list is serializable and allows random access.


1 Answers

If you know that you won't need to add anything to the list later, you can just do

List<Double> myList = Arrays.asList(3.01d, 4.02d, 5.03d);

I'm pretty sure the list returned from Arrays.asList can be modified, but only in that you can change the elements that are there -- you can't add new elements to it.

like image 71
Tyler Avatar answered Oct 28 '22 08:10

Tyler