What does ":" mean in this Java statement?

10,273

Solution 1

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.

Solution 2

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

Solution 3

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());
}
Share:
10,273
Strawberry
Author by

Strawberry

I want to learn industry practices and apply them to my projects to make myself successful

Updated on June 05, 2022

Comments

  • Strawberry
    Strawberry over 1 year
    for (Season time : Season.values() )
    system.out.println (time+ "\t" + time.getSpan());
    

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

  • Strawberry
    Strawberry about 13 years
    Oh I see. I am used to seeing as in PHP.
  • codaddict
    codaddict about 13 years
    @Doug: in PHP you use as. Example: foreach($array as $val)
  • Strawberry
    Strawberry about 13 years
    @codaddict yeah, I made the correcton. You're way ahead of me!
  • Michael Aaron Safyan
    Michael Aaron Safyan about 13 years
    Actually, it is short-hand for the Iterator-based equivalent (since it works with anything that is Iterable).
  • dsmith
    dsmith about 13 years
    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..
  • Brad Mace
    Brad Mace about 13 years
    @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