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 Exploring the Java Collection Framework Using ArrayLists

Nelson Fleig
Nelson Fleig
23,674 Points

Creating Lists with Arrays.asList() vs new ArrayList()

I posted this on the Sets lesson, but I think here would be more appropiate. Sorry for the double post, but I am freaking out with this question =D

I still don't understand when to use the following methods for creating lists. Is there a preference or a difference? The output on java-repl seems to be the same.

List<String> list1 = new ArrayList<String>(); 


List<String> list2 = Arrays.asList("foobar"); 

Is the Arrays.asList() method preferred for creating lists with a length greater than one?

2 Answers

Fahad Mutair
Fahad Mutair
10,359 Points

hi Nelson Fleig ,

in ArrayList

List<String> list1 = new ArrayList<String>(); 

you can add and remove from the List

But, in Arrays.asList()

you can't Add or Remove from the List it will be fixed size list

List<String> list2 = Arrays.asList("foobar"); 
Gonzalo Torres del Fierro
Gonzalo Torres del Fierro
Courses Plus Student 16,751 Points

I had that experience trying to add and remove from the Arrays.asList(), and yes, was impossible to add or remove elements. besides the second one (meaning this Arrays.asList()), allow you to create a list ( the element inside will not have quotes) from an array, and this can be usefull.

I'm not an expert, so take my answer with the appropriate level of salt...

I believe that the Arrays.asList() method is primarily intended to allow a programmer to work with pre-existing arrays that subsequently need to be modified. It was basically a required "work-around" due to the immutable nature of arrays. If you are creating a new list, it is probably a better idea to stick with ArrayList.