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

Bryan Ulziisaikhan
Bryan Ulziisaikhan
620 Points

byArtist() method scope question

So here's the method from the video:

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;
}

What I don't understand is, in the line:

artistSongs.add(song); 

You add a song to the List artistSongs, but that new updated List isn't being put in the map. Why is that?

So the line "artistsSong.add(song)" does nothing because it's not being put in the map. Am I missing something?

1 Answer

It is already there and if it's not (artistSongs == null), it's being put in that if: byArtist.put(song.getArtist(), argistSongs); So the line that you don't get: artistSongs.add(song) is simply adding the song to the List which is already in the map. Try to make sense of the method from top to bottom.

For every song you are attempting to get a reference to the List. If the list doesn't exist, it creates one of type ArrayList. And whether it exists or not (because at the end of the if, it will) you add it to it.

To sum up: .get ... it doesn't exist? new and .put ... finally .add