Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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