Joe
Joe

Reputation: 4542

What is the use of converting Array to ArrayList if it is not supporting adding or removing element?

I have tried the following and saw it throws java.lang.UnsupportedOperationException when I try to add new element to it.

Basically I tried to convert an Array to an ArrayList and tried to add new element to it after concerting from array to ArrayList.

my program is :

public class ArrayToList {
    public static void main(String[] args) {
        String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed income", "futures", "options"}; 
        List<String>  assetList = Arrays.asList(asset);

        for (String object : assetList) {
            System.out.println("object : "+object);
        }

        assetList.add("test");
    }

}

Exception :

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(Unknown Source)
    at java.util.AbstractList.add(Unknown Source)
    at anto.com.collection.ArrayToList.main(ArrayToList.java:15)

What is the use of converting from array to Arraylist if we are not able to add or remove element from converted value?

Thanks

Upvotes: 1

Views: 103

Answers (6)

Saurabh Sharma
Saurabh Sharma

Reputation: 509

Arrays can't be instantiated without passing size. So when you initialize An array giving it's elements[indirectly passing size] and now you are converting it into an ArrayList using asList(arr[]) so this would result into an arraylist of fixed size that you can't modify.

Upvotes: 0

Vinay Pareek
Vinay Pareek

Reputation: 111

For use in other methods that require a List e.g. Collection.sort().

Check this What is purpose of using asList?

Upvotes: 1

devnull
devnull

Reputation: 123708

it throws java.lang.UnsupportedOperationException when i try to add new element to it.

Because it returns a fixed-size list.

Quoting from the documentation:

public static <T> List<T> asList(T... a)

     Returns a fixed-size list backed by the specified array.

If you're consider adding or removing elements, you might be better off using a LinkedList.

List<String> assetList = new LinkedList<String>(Arrays.asList(asset));

Upvotes: 1

Masudul
Masudul

Reputation: 21981

Arrays.asList - returns a fixed-size list backed by the specified array. You can't add new element on fixed size List. To add new element define List as

  List<String>  assetList = new ArrayList(Arrays.asList(asset));

Upvotes: 5

user207421
user207421

Reputation: 311052

Read the Javadoc. Arrays.asList() 'returns a fixed-size list'.

Upvotes: 1

Makoto
Makoto

Reputation: 106528

The resulting list coming from Arrays#asList() is defined to be fixed size. This means that you can't add new elements to it.

If you want to get around it, wrap it in a new ArrayList instead:

List<String> assetList = new ArrayList(Arrays.asList(asset));

Upvotes: 1

Related Questions