Why this List throw UnsupportedOperationException? : A Java Interview Question

Serdar A.
2 min readJul 1, 2023

--

Hello everyone

Let’s first look at our example:

 public static void main(String[] args) {

String[] players = {"Messi","Ronaldinho","Iniesta","Xavi","Busquets","Puyol"};

List<String> list = Arrays.stream(players).toList();

list.remove("Iniesta");

System.out.println("list elements");

list.forEach(s -> System.out.println(s));
}

When we run this code in the console, we see the error Exception in thread “main” java.lang.UnsupportedOperationException.

Exception in thread "main" java.lang.UnsupportedOperationException

In fact, let’s change the code above and try again: Let’s use the add code instead of remove

public static void main(String[] args) {

String[] players = {"Messi","Ronaldinho","Iniesta","Xavi","Busquets","Puyol"};

List<String> list = Arrays.stream(players).toList();

list.add("Valdes");

System.out.println("list elements");

list.forEach(s -> System.out.println(s));
}

When we run this code in the console, we see again the error Exception in thread “main” java.lang.UnsupportedOperationException.

Exception in thread "main" java.lang.UnsupportedOperationException

Why?

Array.asList or Arrays.stream return fixed-size list. For this reason, this error is returned when add or remove operations are performed on the list.

Solution 1:

 public static void main(String[] args) {

String[] players = {"Messi","Ronaldinho","Iniesta","Xavi","Busquets","Puyol"};

// List<String> list = Arrays.stream(players).toList();
//
// list.remove("Iniesta"); //error

List<String> list = new ArrayList<>();
list.addAll(Arrays.stream(players).toList());

list.remove("Iniesta");
System.out.println("list elements");

list.forEach(s -> System.out.println(s));

}

Solution 2:

    public static void main(String[] args) {

String[] players = {"Messi","Ronaldinho","Iniesta","Xavi","Busquets","Puyol"};

// List<String> list = Arrays.stream(players).toList();
//
// list.remove("Iniesta"); //error

List<String> linkedList = new LinkedList<>(Arrays.asList(players));
linkedList.add("Valdes");

System.out.println("linked list elements");

linkedList.forEach(s -> System.out.println(s));
}

Thanx for reading :)

--

--

Serdar A.

Senior Software Developer & Architect at Havelsan Github: https://github.com/serdaralkancode #Java & #Spring & #BigData & #React & #Microservice