Adding items to ArrayList: one at a time is no fun!

In the Android app with Java course, I’m currently in the “Java Arrays and Loops” chapter, trying the “Desert Island Playlist” project.

Task 3. wants us to use the add() method to add songs to the Playlist. That allows us to add only one at a time, having to write out e.g.
desertIslandPlaylist.add("Quantic - Hold It Down");
five times for five songs.
Surely there must be a shorter, more fun way to batch-add a number of elements to a list?

You can probably write a function that adds n items, given some input file that’s specifically formatted.

For example if you have a file with entries like
Artist: Foo Title: Bar Publisher: Baz

The function you write would first read the file line by line, and parse the specific data you wanted to input (and finally use your add() function.

1 Like

Well that looks like it’d be way more work than typing one add() statement for each element I want to add, unless we’re maybe talking in the dozen to hundreds of elements.
I was thinking more along the lines of a better utility method for populating an list - provided by Java, maybe some library. Could it be that nothing of the likes exists?

If you wanted to type it all in one string with some delimiter like # you could write a simple function that takes a large string and parses it like you want.

Example string: Band1 - Song1#Band2 - Song2#Band3 - Song4

Alternatively you can have a while loop that keeps prompting you to enter songs until you hit a special quit command.

1 Like