开发者

Using the ":" operator

I 开发者_如何学运维know this is a basic question, but all the documentation I read doesn't seem to answer my question: What does the ":" operator do?

I get the impression that if I do something like for(item : list), the for loop would go through every item of a list. Is this right?


Yes, what you have there is a for each statement. The one you have is not quite correct, if you have a List<String> called list for example then you could do something like this:

for (String item: list) {
   System.out.println(item);
}

As an aside there is also another use for ":" as part of a ternary expression, e.g.

int i = y < 0 ? 10 : 100;

which is the same as:

int i;

if (y < 0) {
   i = 10;
} else {
   i = 100;
}


Yes, that's right. It's not really an operator as such - it's part of the syntax for the enhanced for loop which was introduced in Java 5.


Yes. If you have an iterable object, you can do something like:

for (Object o : iterableObj) {
    o.doSomething();
}

which is equivalent (in functionality) to something like:

for (int i = 0; i < iterableObj.length(); i++) {
    Object o = iterableObj.get(i);
    o.doSomething();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜