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.
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? Explanation: List returned by Arrays. asList() is a fixed length list which doesn't allow us to add or remove element from it.
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.
asList returns a fixed-size list that is backed by the specified array; the returned list is serializable and allows random access.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With