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 Using ArrayLists

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,750 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.