Reputation: 788
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?
Upvotes: 50
Views: 54339
Reputation: 12999
These days the streams API can easily get you an ArrayList
in a concise and functional manner:
Stream.of("str1", "str2").collect(Collectors.toList()));
Of course this also has the flexibility to transform using mappings. For example, while writing unit tests for Spring security code it was convenient to write the following:
Stream.of("ROLE_1", "ROLE_2").map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
The list returned by Collectors.toList
is an ArrayList
and may be modified as required by your code.
Upvotes: 3
Reputation: 1
ArrayList<Object> MyObjectList = new ArrayList<>();
Arrays.asList(params[1]).forEach((item)-> {
MyObjectList.add(item);
});
Upvotes: 0
Reputation: 41
Arrays.asList()
generates an unmodifiable list on object creation. You can use the below code.
List list = Collections.synchronizedList(new ArrayList(...));
This convert allows the list to add and remove objects. I have only tested in java 8.
Upvotes: 0
Reputation: 9406
You can get around the intermediate ArrayList
with Java8 streams:
Integer[] array = {1, 2, 3};
List<Integer> list = Streams.concat(Arrays.stream(array),
Stream.of(4)).collect(Collectors.toList());
This should be pretty efficient as it can just iterate over the array and also pre-allocate the target list. It may or may not be better for large arrays. As always, if it matters you have to measure.
Upvotes: 4
Reputation: 4524
Arrays.asList(),generates a list which is actually backed by an array and it is an array which is morphed as a list. You can use it as a list but you can't do certain operations on it such as adding new elements. So the best option is to pass it to a constructor of another list obj like this:
List<T> list = new ArrayList<T>(Arrays.asList(...));
Upvotes: 6
Reputation: 11486
The Constructor for a Collection, such as the ArrayList, in the following example, will take the array as a list and construct a new instance with the elements of that list.
List<T> list = new ArrayList<T>(Arrays.asList(...));
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)
Upvotes: 3
Reputation: 500367
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.
Upvotes: 15
Reputation: 213261
Create a new ArrayList
using the constructor:
List<String> list = new ArrayList<String>(Arrays.asList("a", "b"));
Upvotes: 87