Java Java Data Structures Exploring the Java Collection Framework Sets

James Adamski
James Adamski
3,027 Points

Unsupported operation error in java-repl

Can you see the source of the error below in java-repl. I tried various solutions, including, trying to manually import the java.utils. Don't understand why it should fail here.

ava> List<String> frontEndLang = Arrays.asList("HTML","CSS","JavaScript","TypeScript");
java.util.List<java.lang.String> frontEndLang = [HTML, CSS, JavaScript, TypeScript]
java> List<String> backEndLang = Arrays.asList("Java","Python","JavaScript","PHP","Objective-C","Swift","Ruby");
java.util.List<java.lang.String> backEndLang = [Java, Python, JavaScript, PHP, Objective-C, Swift, Ruby]
java> List<String> allLangs = Arrays.asList("HTML","CSS","JavaScript","TypeScript");
java.util.List<java.lang.String> allLangs = [HTML, CSS, JavaScript, TypeScript]
java> allLangs.addAll(backEndLang);

1 Answer

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,770 Points

James Adamski Arrays.asList() method of java.util.Arrays class acts as bridge between the standard Array and Java Collection Framework. Arrays.asList() method returns a fixed-size list meaning you cannot add or remove elements. This method is really useful when you wish to manually insert elements to a List and saves you time instead of calling .add() everytime you want to insert and element to a Collection List.

However it has a downside in that the array won't dynamic and cannot be increased/decreased in size . As an indication that the code is trying to modify a non-resizable or unmodifiable collection, UnsupportedOperationException is thrown if you try to add or remove elements.

To add/remove elements you need to wrap your list in a new ArrayList e.g.

List<String> allLangs = new ArrayList<>(Arrays.asList("HTML","CSS","JavaScript","TypeScript"));