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

Adding to the list of artist songs that exist in the map for that specific artist

In the method byArtists...

Why does the list of artist songs within the map update when you add the song to the List<String>. That line of code is after the line in which the empty ArrayList is added to the key of that artist. it steps out of the if statement where it is declared and puts the new song in the list and instantly updates the map. I don't see how this happens.

Martin Gallauner
Martin Gallauner
10,808 Points

Hi Garrett

This is because the Lists is a part of the Map. You have for every key(Artists) a value (artistSongs).

When you go through all you Songs (mSongs) you add them to the SongList for the Artist.

IF there is no Key for this Artist, then you put a new Key there with it's own list

 private Map<String, List<Song>> byArtist() {
    Map<String, List<Song>> byArtist = new HashMap<>();
    for (Song song : mSongs
        ) {
      List<Song> artistSongs = byArtist.get(song.getArtist());
      if (artistSongs == null) {
        artistSongs = new ArrayList<>();
        byArtist.put(song.getArtist(), artistSongs);
      }
      artistSongs.add(song);
    }
    return byArtist;
}
Sudershan Pothina
Sudershan Pothina
9,849 Points

The part where I don't understand is how is the Map byArtist being updated, if we are only adding the artist and the song using the put method in the IF condition. And if we are creating a new instance of the artistSongs variable, How and where are the other instances stored?