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

The order of adding to artistSongs

I am confused about the order of actions in the following method.

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

In the if statement it creates the new ArrayList so that we can add to it but that seems to be just the problem. An entry looks as if it is being made in byArtist with an empty ArrayList. And after the entry has been put in, the song is THEN added to artistSongs. Wouldn't a list of one song just create an new entry with an empty array?

1 Answer

Jeff Froustet
Jeff Froustet
16,015 Points

I think what you're getting confused on (and please correct me if I'm wrong) is how the code seems to add an empty list (artistSongs) as the value for a particular artist/key in the byArtist map. A song is eventually added to that empty artistSongs list, but only after the list was put into byArtist. So how could byArtist ever be updated to include a song? It seems like the list in byArtist would always be empty! This had me confused until I remembered what we learned about objects and references to objects. In the for loop we start off with an empty byArtist HashMap. We declare and initialize the artistSongs List with a value from byArtist, but artistSongs is null because byArtist is empty. We hit the if statement and it runs its code because, again, artistSongs is null. The if statement then initializes artistSongs as an empty ArrayList and adds a "John Smith": artistSongs pair/entry to byArtist. The if statement ends, and then we add the song to that empty artistSongs list. Here's the kicker -- adding a song to artistSongs updates byArtist. Remember, byArtist is pointing to artistSongs. Don't think of it as adding an empty list to byArtist. Think of it as adding artistSongs to byArtist. If you change artistSongs by adding a song, you change byArtist because its value is a reference to the artistSongs object.