Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add elements in List when used Arrays.asList()

Tags:

java

list

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?

like image 862
Praful Surve Avatar asked Aug 22 '13 19:08

Praful Surve


People also ask

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.

How is array asList () different?

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.

Can we add elements to arrays asList?

asList is fixed in size. A simple test will confirm that you can neither add elements to nor remove elements from the list.

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.


2 Answers

Create a new ArrayList using the constructor:

List<String> list = new ArrayList<String>(Arrays.asList("a", "b")); 
like image 110
Rohit Jain Avatar answered Oct 08 '22 09:10

Rohit Jain


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.

like image 36
NPE Avatar answered Oct 08 '22 10:10

NPE