开发者

What does ":" mean in this Java statement?

开发者 https://www.devze.com 2023-01-21 02:12 出处:网络
for (Season time : Season.values() ) system.out.println (time开发者_运维百科+ \"\\t\" + time.getSpan());
for (Season time : Season.values() )
system.out.println (time开发者_运维百科+ "\t" + time.getSpan());

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


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.


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


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());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号