Java
List.add() method
UnsupportedOperationException
Programming errors
Debugging in Java

Java List.add() UnsupportedOperationException

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In Java, the List.add() method is used to add an element to a list. However, under certain conditions, using this method may throw an UnsupportedOperationException. This exception generally occurs when an attempt is made to modify a list that does not support modification.

Understanding UnsupportedOperationException

The UnsupportedOperationException is a runtime exception thrown by methods that have not been implemented by a particular class. In the context of collections, it commonly arises with immutable collections or those whose modification is otherwise restricted.

Scenarios Where UnsupportedOperationException Occurs

  1. Immutable Collections: Collections obtained from methods such as Collections.unmodifiableList() are immutable. Any attempt to add or remove elements from such a list will result in an UnsupportedOperationException.
  2. Fixed-size Lists: Lists created from arrays with Arrays.asList() are backed directly by the array, making their size fixed. Trying to add elements to such lists will throw the exception because it would require dynamic resizing which these lists do not support.
  3. Other Collections that Prohibit Modifications: Certain implementations of List may choose to restrict modifications depending on their specific use case or internal structure.

Technical Explanation

In Java, collections come with varying degrees of modification capabilities. It is these capabilities that determine whether a list supports operations like add(), remove(), etc. For example, consider the following usage scenarios:

java
1List<String> fixedSizeList = Arrays.asList("Apple", "Banana", "Cherry");
2fixedSizeList.add("Date"); // Throws UnsupportedOperationException
3
4List<String> unmodifiableList = Collections.unmodifiableList(new ArrayList<>(Arrays.asList("X", "Y", "Z")));
5unmodifiableList.add("W"); // Throws UnsupportedOperationException

In both examples, the List instances do not support the add operation because of the immutable or fixed-size nature of the underlying list.

Code Example and Explanation

Here is another example and a breakdown of why it throws an UnsupportedOperationException:

java
1import java.util.*;
2
3public class Main {
4    public static void main(String[] args) {
5        List<Integer> originalList = new ArrayList<>(Arrays.asList(1, 2, 3));
6        List<Integer> subList = originalList.subList(1, 3);
7        
8        subList.add(4); // This line might throw UnsupportedOperationException
9        System.out.println("SubList: " + subList);
10        System.out.println("Original List: " + originalList);
11    }
12}

In this example, subList may seem like a regular List, but it directly reflects the specified range of the original list. If the underlying list's structure does not allow for dynamic changes (e.g., elements addition or removal), trying to manipulate the sublist could cause an UnsupportedOperationException.

Mitigation Strategies

When faced with this exception, you should:

  1. Verify the Type of the List: Check whether the list is indeed modifiable by inspecting its type and origin. Use documentation to see if the list type naturally prohibits modification.
  2. Use a Modifiable List: If modification is essential, consider copying the elements into a fully modifiable list like ArrayList:
java
    List<String> modifiableList = new ArrayList<>(Arrays.asList("A", "B", "C"));
    modifiableList.add("D");
  1. Review API Documentation: Always review the Java API documentation for the behavior of the list implementation being used. Different implementations have different modification policies.

Summary Table

Method/SourceAllow ModificationsException Risk
Arrays.asList()NoHigh
Collections.unmodifiableList()NoHigh
ArrayList<>()YesLow
Original List.subList()ConditionalMedium to High

Conclusion

The UnsupportedOperationException in the context of Java's List.add() method is typically associated with scenarios where modifications to a list are not supported. Understanding the specific characteristics of the list you are working with, whether in terms of its mutability, size restrictions, or the consequences of its derived nature, is crucial for effective Java programming and avoiding runtime exceptions like UnsupportedOperationException.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.