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 - Retired Efficiency! Implement Chooser UI

Problem understanding line of code in Songbook

Hi, I had problems with this line of code:

List<Song> artistSongs = byArtist.get(song.getArtist());

I don't understand what it does. It creates a new List named after the artist? Can you create a list name with a variable? Thanks :)

Marcus Karlsson
Marcus Karlsson
1,291 Points

Not named after the artist, after the artist's songs.

Your method is of the type Map<String, List<Song>> byArtist() so what your line of code does is to check if the artist you're looking for has any songs in the List artistSongs. "(That is why it says byArtist.get(song.getArtist()))" so through your map method your are checking the keyValue(String) which is the artist's name and if that name is connected to any songs.

Can be a bit confusing but hope that makes it a little easier to grasp.

1 Answer

Nelson Fleig
Nelson Fleig
25,764 Points

Also my question. Wouldn't adding an element to the list without using the add method result in overwriting list elements? Why isn't Craig using the add method?

i.e.:

List<Song> artistSongs;
artistSongs.add(byArtist.get(song.getArtist()));
>>>.  artistSongs.add(byArtist.get(song.getArtist())); << song.getArtist() returns string artist's name
>>>1. artistSongs.add(byArtist.get("Marylin Manson"); << byArtist.get("Marylin Manson") returns (should) value of this key but there is not value for key "Marylin Manson" yet so returns "null"
>>>2. artistSongs.add(null);
>>>3. artistSongs returns null not list of songs.