'Java Collections immutable [duplicate]

This program is running fine but when I try to run the code with any of these commented-out statements it throws an "UnsupportedOperationException" error and I can't figure out why. I don't want to add elements to the list Individually.

/* 
    List<String> strings =Arrays.asList("Namste", "India", "..!"); 
    --> java.base/java.util.AbstractList.add      
*/

/*     
List<String> strings =List.of("Namste", "India", "..!");
    --> java.util.ImmutableCollections$AbstractImmutableCollection.add      
*/
List<String> strings =new ArrayList<>();                
strings.add("Namaste");
strings.add("India");
strings.add("..!");
        
System.out.printf("Before : ");
for (String string : strings) 
     System.out.printf("%s ",string);
        
Methods.addAll(strings, "G","K");        

System.out.printf("\nAfter : ");
for (String string : strings) 
     System.out.printf("%s ",string);

Methods.addAll is defined like this:

public static <T> void addAll(List<T> list, T... arr) {
        for (T elt : arr) list.add(elt);
}


Solution 1:[1]

Arrays.asList() and List.of() will both produce Lists that are immutable.

To use them for a list you would like to extend, you could do something like

List<String> strings = new ArrayList<>(List.of("Namste", "India", "..!"));

Solution 2:[2]

This has nothing to do with varargs or generics. The lists you're creating in the commented-out section are immutable: ImmutableCollections$AbstractImmutableCollection is, for example, an immutable collection. That means you can't change it, for example by adding to it. (Arrays.asList isn't fully immutable: you can replace entries via set, you just can't add or remove any -- the list length is immutable.)

The JavaDocs make this clear, and I'd encourage you to read them carefully as "first line of defense" when you have a question about a class's behavior. The docs for Arrays.asList specify that it's "fixed-size", while the docs for List.of describe it as an "unmodifiable list", with a link to a page describing exactly what that means.

A standard one-liner to get a mutable list is new ArrayList<>(Arrays.asList(your, elements, here)). That generates the half-immutable Arrays.asList, and then adds its elements to a new ArrayList.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2