views:

142

answers:

3
for (Season time : Season.values() )
system.out.println (time+ "\t" + time.getSpan());

I see an example for enumeration using :. What does this mean?

+5  A: 

This is the Java syntax for a foreach loop.

The loop will iterate over all the items in the collection of objects returned by Season.values() one at a time, putting each item in turn into the time variable before executing the loop body. See this closely related question for more details on how the foreach loop works.

Cameron
Oh I see. I am used to seeing `as` in PHP.
Doug
@Doug: in PHP you use `as`. Example: `foreach($array as $val)`
codaddict
@codaddict yeah, I made the correcton. You're way ahead of me!
Doug
+1  A: 

It is just a token to separate the iterating variable on the left from the array on the right in the new for-each loop

codaddict
+1  A: 

It's java's version of foreach.

It's a shorthand version of

for (int i = 0; i < Season.values().size(); i++) {
    Season time = Season.values().get(i);
    System.out.println(time + "\t" + time.getSpan());
}

(exact details depend on what it is that Season.values() is returning, but you get the idea)

As Michael points out, while the above example is more intuitive, foreach is actually the equivalent of this:

Iterator<Season> seasons = Season.iterator();
while (seasons.hasNext()) {
    Season time = seasons.next();
    System.out.println(time + "\t" + time.getSpan());
}
bemace
Actually, it is short-hand for the Iterator-based equivalent (since it works with anything that is Iterable).
Michael Aaron Safyan
@Michael - good point, example added for posterity
bemace
In what universe is using a for to do an indexed iteration over a container more intuitive than using Iterator semantics. Each to their own I suppose..
dsmith
@dsmith - when I say "more intuitive", I meant in terms of explaining what foreach does. Since it's still structured as a `for`-loop, I think it's easier for people to relate what's going on if they're seeing a for-each construct for the first time
bemace