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

Lingjian Kong
Lingjian Kong
6,330 Points

artistSongs.add(song)

Hi,

In

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

We have artistSongs.add(song);

When we are not creating a new song list for a new artist, it seems to me that it only adds the song to the local List "artistSongs", without putting it into the map by "byArtist.put(song.getArtist(), artistSongs);" Why don't we add byArtist.put(song.getArtist(), artistSongs); after artistSongs.add(song);?

Could someone clarify it for me?

1 Answer

Vidhya Sagar
Vidhya Sagar
1,568 Points

Yes you can. It is perfectly legal to do that. Since it is a List<Song> type and it is a list it will get updated instantaneoulsy at runtime. But when you do that if the Map has not been created then it will come inside the if and add the song and since there is no else statement it will continue and add the song again , because there is an add option again outside the if condition . One way is by using else. IF you use else , then what you are suggesting will work. or the song will get added twice(one for add inside the if and again one for the add outside the if) whenever a new Map is created. Hope this helps.