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

Please Help me

hey would you please help me with this

e.g. List<Song> mSongs = new ArrayList<>();

for(Song song: msongs)

I know the song is the variable of type Song but how it works, like in the msongs case how it will get all the data from Song. please explain me. Thank You!

1 Answer

Simon Coates
Simon Coates
28,694 Points

the : reads as "in". You can read the line as "for each song in msongs". The idea is that a block of code will repeat and for each iteration, the next value in the collection will be placed in a variable called 'song'. A related demo might be:

import java.util.*;

class Main {
  public static void main(String[] args) {
    List<String> strings = new ArrayList<>();
    strings.add("first");
    strings.add("second");
    for(String string: strings){
      System.out.println(string.toUpperCase());

    }
  }
}

produces

FIRST
SECOND

This demos that each value is able to be accessed with a single variable name. The variable type is necessary and determines what you can do with the value. Here, as i've created a list of strings, i'm able to access a method on that class. (toUpperCase). For your purposes, a list containing instances of Song determines how you can use the item (fields, methods).