Home > Net >  Java Generic and Vararg
Java Generic and Vararg

Time:02-28

This program running fine buy When i try to run the code with any of these commented out statement it throw an "UnsupportedOperationException" error and i don't figure it out why? and i don't want to add elements in list Individually. :(

May be this is a silly Question. :(

/* 
    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 Defined like that :

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

CodePudding user response:

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", "..!"));

CodePudding user response:

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.

  • Related