Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired 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);
java.lang.UnsupportedOperationException

1 Answer

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 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"));