使用“:”操作员
我知道这是一个基本问题,但我阅读的所有文档似乎都没有回答我的问题:“:”运算符的作用是什么?
我的印象是,如果我执行类似 for(item : list)
的操作,for 循环将遍历列表中的每个项目。这是对的吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您所拥有的每个语句都有一个。您所拥有的不太正确,例如,如果您有一个名为 list 的
List
,那么您可以执行以下操作:顺便说一句,“:”作为一部分还有另一种用途三元表达式的,例如
与以下相同:
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:As an aside there is also another use for ":" as part of a ternary expression, e.g.
which is the same as:
是的,没错。它并不是真正的运算符 - 它是 增强的 for 循环,在 Java 5 中引入。
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:
which is equivalent (in functionality) to something like: