Java for 循环语法:“for (T obj : objects)" [英] Java for loop syntax: "for (T obj : objects)"

查看:36
本文介绍了Java for 循环语法:“for (T obj : objects)"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些我以前从未见过的 Java 语法.我想知道是否有人可以告诉我这里发生了什么.

I came across some Java syntax that I haven't seen before. I was wondering if someone could tell me what's going on here.

for (ObjectType objectName : collectionName.getObjects())

推荐答案

它被称为for-each增强的for语句.参见JLS §14.14.2.

它是语法糖,由编译器提供,用于迭代Iterables 和数组.以下是迭代列表的等效方法:

It's syntactic sugar provided by the compiler for iterating over Iterables and arrays. The following are equivalent ways to iterate over a list:

List<Foo> foos = ...;
for (Foo foo : foos)
{
    foo.bar();
}

// equivalent to:
List<Foo> foos = ...;
for (Iterator<Foo> iter = foos.iterator(); iter.hasNext();)
{
    Foo foo = iter.next();
    foo.bar();
}

这是遍历数组的两种等效方法:

and these are two equivalent ways to iterate over an array:

int[] nums = ...;
for (int num : nums)
{
    System.out.println(num);
}

// equivalent to:
int[] nums = ...;
for (int i=0; i<nums.length; i++)
{
    int num = nums[i];
    System.out.println(num);
}

进一步阅读

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆