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

David Pollard
David Pollard
4,324 Points

Struggling with understanding of this Java code

I'm trying to get my head around this code. What I understand is added as remarks. The question comes towards the end :-

// Create a method called byArtist() that returns a hashmap of Artist name
// and for each artist a list of songs by them.
 private Map<String, List<Song>> byArtist() {

// Create the object we're eventually going to return (byArtist) that is a new hashmap of
// artist and their list of songs
    Map<String, List<Song>> byArtist = new HashMap<>();

// For each song in the songlist
    for (Song song : mSongs) {

// Check if there is a array list of songs for the artist in question
      List<Song> artistSongs = byArtist.get(song.getArtist());

// if there's not
      if (artistSongs == null) {

// then create one.
        artistSongs = new ArrayList<>();

// and initialize it with the artist name, and the new blank arraylist
        byArtist.put(song.getArtist(), artistSongs);
      }

// this is where i struggle. we seem to only add the song to the list,
// we don't ever seem to update byArtist with the list of songs ! :-(
// apart from when there is no arraylist (i.e. it's null) ?!?!?!

  artistSongs.add(song);
    }

    return byArtist;
  }

Thanks ! :-)

dp

1 Answer

Eitan Vinsonneau
Eitan Vinsonneau
2,498 Points

artistSongs is actually a reference (a pointer to place in memory if you will). So when you do artistSongs.add(song) it modify the ArtistSong that is in byArtist.

I suggest you lookup "java object reference" or "C pointer" for more info and there's also a treehouse workshop in the java course (concerning Strings if I remember correctly) where this is explained in great details.

Also why do you hate other programmers so much as to give the same name to a function and a variable ?

David Pollard
David Pollard
4,324 Points

Eitan - thanks so much - that is definitely what I was missing. Makes sense now - much appreciate your time.

As for this :-

Also why do you hate other programmers so much as to give the same name to a function and a variable ?

I also didn't feel comfortable with that, but that's the code used in the tutorial, not my code ! :-)