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 trialAbhinav Kanoria
7,730 PointsConverting array of Strings to an ArrayList<String>
Consider the following lines of code: String[] languages = {"English", "French", "Thai", "Spanish", "Korean", "Chinese"}; List<String> langList = new ArrayList<String>(); langList = Arrays.asList(languages);
If I execute the command langList.get(3) to get the language at position 3, I get Spanish as expected. But when I want to add another language to the langList ArrayList, i.e., when I do
langList.add("Hindi"); I get an 'UnsupportedErrorException'. SO why can't I add more languages to langList?? I cannot remove exixting languages(like French, Korean) from langList as well. Please help. Thanks!
2 Answers
Seth Kroger
56,414 PointsBecause Arrays.asList() is fixed size, what you want to do is copy that list in into a new ArrayList. You can accomplish this with:
List<String> langList = new ArrayList<String>(Arrays.asList(languages));
Andre Luis Araujo Santos
3,241 PointsWell, having a look in this the oracle documentation:
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)
This method returns a fixed-size List, which means that we can't change its size (add or remove elements). It's like a regular array with its specified size, but with the List methods (except the methods add/remove, I suppose).
Abhinav Kanoria
7,730 PointsThanks a lot. That helped!
Abhinav Kanoria
7,730 PointsAbhinav Kanoria
7,730 PointsHi Seth! Thanks a lot. This one worked for me. I can now add and remove languages from my langList. But can you explain why you passed Arrays.asList(languages) as a parameter? How is doing this different from doing List<String> langList = new ArrayList<String>(); langList = Arrays.asList(languages);