Modifying Collections Returned by Arrays.asList() in Java

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Can you modify the collection return by Arrays.asList()?

Answer:

No, the collection returned by Arrays.asList() is a fixed-size list backed by the original array. This means that while you can modify the elements of the list (e.g., change the value of an element), you cannot add or remove elements from the list. Attempting to do so will result in an UnsupportedOperationException.

Here's an example to illustrate this:

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String[] array = {"A", "B", "C"};
        List<String> list = Arrays.asList(array);

        // Modifying an element
        list.set(1, "Z"); // This is allowed
        System.out.println(list); // Output: [A, Z, C]

        // Trying to add an element
        // list.add("D"); // This will throw UnsupportedOperationException

        // Trying to remove an element
        // list.remove(0); // This will also throw UnsupportedOperationException
    }
}

In this example, you can see that modifying an existing element is allowed, but trying to add or remove elements will result in an exception. If you need a modifiable list, you can create a new ArrayList from the fixed-size list:

List<String> modifiableList = new ArrayList<>(list);
modifiableList.add("D"); // Now this is allowed

This way, you can freely add or remove elements from modifiableList.