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

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

codaddict
  • 445,704
  • 82
  • 492
  • 529
Strawberry
  • 66,024
  • 56
  • 149
  • 197

3 Answers3

7

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.

Community
  • 1
  • 1
Cameron
  • 96,106
  • 25
  • 196
  • 225
1

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
  • 445,704
  • 82
  • 492
  • 529
1

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());
}
Brad Mace
  • 27,194
  • 17
  • 102
  • 148
  • 1
    Actually, it is short-hand for the Iterator-based equivalent (since it works with anything that is Iterable). – Michael Aaron Safyan Oct 22 '10 at 03:28
  • 1
    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 Oct 22 '10 at 03:42
  • 1
    @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 – Brad Mace Oct 22 '10 at 03:44