We cannot perform <Collection>.add
or <Collection>.addAll
operation on collections we have obtained from Arrays.asList
.. only remove operation is permitted.
So What if I come across a scenario where I require to add new Element in List
without deleting previous elements in List
?. How can I achieve this?
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 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.
asList is fixed in size. A simple test will confirm that you can neither add elements to nor remove elements from the list.
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.
Create a new ArrayList
using the constructor:
List<String> list = new ArrayList<String>(Arrays.asList("a", "b"));
One way is to construct a new ArrayList
:
List<T> list = new ArrayList<T>(Arrays.asList(...));
Having done that, you can modify list
as you please.
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