If you are getting an UnsupportedOperationException while adding an object to List the reason could be that you are performing this operation on a fixed-size List object.
What is a fixed-length object?
You must have used Arrays.asList method to convert an array object to List object. If you closely look at the documentation of Arrays.asList method, it says that, Arrays.asList method returns a fixed-size list backed by the specified array, which means that the returned List is of a fixed size. You cannot change the structure as you do to a normal List. That is, you cannot add or remove elements to this List. This List object has a direct relation with the array from which it is created. Any change you make to the object within the List will get updated within the array also. Similarly, any change you make to the array object will get reflected in the List object as well.
Example
Below example will result in UnsupportedOperationException as it is trying to add new element to a fixed-size List object.
package com.techstackjournal;
import java.util.Arrays;
import java.util.List;
public class ArrayToList {
public static void main(String[] args) {
String[] arr = { "Alpha", "Beta", "Gamma" };
List<String> list = Arrays.asList(arr);
list.add("Theta");
for (Object object : list) {
System.out.println(object);
}
}
}
Output:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractList.add(AbstractList.java:153)
at java.base/java.util.AbstractList.add(AbstractList.java:111)
at com.techstackjournal.ArrayToList.main(ArrayToList.java:14)
So, How to fix this UnsupportedOperationException?
If your objective is to copy elements from array to List and add further elements to the List, then the approach to copy the elements from array to List using Arrays.asList is not correct. You should better go for other alternative approaches, which I explained in my “How to Convert an Array to List in Java?” post.