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 trialPrasoon Shukla
3,426 PointsArray to List conversion
In Main.java, what is the purpose of doing: List<String> fakeResults = Arrays.asList() ?Why are we converting array as list? Can we not use a list directly here?
1 Answer
Grigorij Schleifer
10,365 PointsHi Prasoon,
I think the main reason why you convert an array into a List is because Lists are much easier to use and have much more functionality.
Array is static in size that is fixed length data structure, One can not change the length after creating the Array object. So if you have an array and it can hold 6 primitives and suddenly you want to add more then 6 items into it. You can´t ! You will need to create a bigger array and combine them together and so on .... ugly right :)
List is an interface in Java, which means that it may have multiple implementations. One of these implementations is ArrayList, which is a class that implements the behavior of the List interface using arrays as the data structure.
So if you convert an array into List and implement/add the functionality of an ArrayList for example, you can add items into this List/ArrayList and enjoy it. Because elements are added to an ArrayList its capacity grows automatically.
Here is a great comparison between ArrayList and array:
http://javahungry.blogspot.com/2015/03/difference-between-array-and-arraylist-in-java-example.html
I hope i could help :)
Grigorij
Prasoon Shukla
3,426 PointsThanks Grigorij! So can I say that use of array here is more because of 'best-practice' here and the code would have run even if we just use plain simple list here? (Although I understand now why it is important to use Array List).
Edit: I just realized we would need an array list here because we want the user to give as many inputs (names, nouns, adjectives) in their story. If we use a list here, this would only allow user to give inputs in the list and not based on the number of placeholders( name) in the story.
Thanks for your help!
Grigorij Schleifer
10,365 PointsGrigorij Schleifer
10,365 PointsHey Prasoon,
glad I could help :)
See you in the forum
Grigorij