50

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?

Praful Surve
  • 788
  • 1
  • 10
  • 22
  • Why can't you add? `asList` returns a `new ArrayList`. Oh, it's not the same `ArrayList` – Sotirios Delimanolis Aug 22 '13 at 19:14
  • 7
    @SotiriosDelimanolis Lists returned by Arrays.asList are backed by the array passed in, and are unmodifiable. From [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)) (emphasis added), "Returns a ***fixed-size list*** backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess." – Joshua Taylor Aug 22 '13 at 19:15
  • 1
    @JoshuaTaylor Had not noticed it was `java.util.Arrays.ArrayList` – Sotirios Delimanolis Aug 22 '13 at 19:16
  • @SotiriosDelimanolis Well, the javadoc only guarantees that's it's a fixed size list, though yes, it does seem that's it's an `java.util.Arrays$ArrayList`. `java.util.ArrayLists`, of course, are, in general, modifiable. – Joshua Taylor Aug 22 '13 at 19:19
  • @JoshuaTaylor `java.util.Arrays.ArrayList` extends `AbstractList` which throws `UnsupportedOperationException()` for some of the methods. – Sotirios Delimanolis Aug 22 '13 at 19:19
  • @SotiriosDelimanolis Right; my point is that _the javadoc_ doesn't guarantee that you'll get a `java.util.Arrays.ArrayList` back, just that you'll get a fixed size `List` (so it makes sense that it throws an `UnsupportedOperationException` when attempts are made to change its size). However, `java.util.ArrayList` (not the `java.util.Arrays$ArrayList`) is a "resizable-array implementation of the List interface", according to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html). – Joshua Taylor Aug 22 '13 at 19:23
  • 1
    @prafulsurve The remove operation isn't permitted either; the list returned by Arrays.asList is fixed in size. A simple test will confirm that you can neither add elements to nor remove elements from the list. – Joshua Taylor Aug 22 '13 at 19:27

8 Answers8

85

Create a new ArrayList using the constructor:

List<String> list = new ArrayList<String>(Arrays.asList("a", "b"));
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
15

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
6

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(...));
Mr.Q
  • 4,316
  • 3
  • 43
  • 40
4

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.

Jens
  • 9,058
  • 2
  • 26
  • 43
3

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)

blackpanther
  • 10,998
  • 11
  • 48
  • 78
3

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.

Andy Brown
  • 11,766
  • 2
  • 42
  • 61
0

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.

Fatih
  • 21
  • 6
0
ArrayList<Object> MyObjectList = new ArrayList<>();
Arrays.asList(params[1]).forEach((item)-> {
    MyObjectList.add(item);
});
  • 3
    Thanks for your contribution! However, you should add a few comments to your answer to explain what advantage your solution has over the accepted answer, or what other new circumstances make your solution more attractive. – Patrick Sep 09 '20 at 02:25