Adding to the top of the throw list?

Trying to use the following to add to the top of the list, but throws to add. Doc says he needs to move. What is a fix or workaround?

List<String> whatever = Arrays.asList("Blah1", "Blah2"); whatever.add(0, "BlahAll"); // <- Throws 
+4
source share
6 answers

List generated by Arrays.asList() is not an ArrayList , but another list that does not support this operation (the contract for List says add() is optional)

As a workaround, you can do this:

 List<String> whatever = new ArrayList(Arrays.asList("Blah1", "Blah2")); whatever.add(0, "BlahAll"); 
+4
source

You cannot add an item to a list created using Arrays.asList() . As the documentation reports:

Returns a fixed size list supported by the specified array.

+5
source

Arrays.asList returns an array of a fixed size. If you want to add additional elements, you need to create another List object, possibly with whatever = new ArrayList<String>(array) .

+4
source

What does it throw, UnsupportedOperationException? add () in the list is documented as an “optional operation”. When you created a list using Arrays.asList (), it does not create any new data structures, it just uses the existing array as the basis for performing operations with List (I think). This makes insertion impossible.

You will need to decide another implementation of your list, such as LinkedList:

 List<String> whatever = new LinkedList<String> (Arrays.asList("Blah1", "Blah2")); 

(I have not tested this.)

+3
source

Here you used arrays instead of a list of arrays.

Read This Before Fixing Your Question

The main difference between Array and ArrayList in Java is that the Array is a structure fixed data length, and ArrayList collection class is of variable length.

You cannot change the length of the array after creation in Java, but the ArrayList re-parses itself when populated depending on capacity and load factor.

Because Array List is internally maintained by Array in Java, any resizing operation in ArrayList will slow performance, as it involves creating a new array and copying the contents from the old array to the new array .

But here you need to use an ArrayList. Since you need to add data at a later stage.

 List<String> whatever = new ArratList(Arrays.asList("Blah1", "Blah2")); whatever.add(0, "BlahAll"); 
+1
source

Try google library,

 import com.google.common.collect.Lists; List<String> whatever = Lists.newArrayList("Blah1", "Blah2"); whatever.add(0, "BlahAll"); 
+1
source

Source: https://habr.com/ru/post/1497165/


All Articles