名为people的列表通常包含Person对象.
这是一些示例代码,演示如何使用for-each循环:
public class Demo {
private static class Person {
public int age;
public String name;
public Person(int age,String name) {
this.age = age;
this.name = name;
}
}
public static void main(String... args) {
// Create and populate a list of people with individuals
List people = new ArrayList<>();
people.add(new Person(32,"Fred"));
people.add(new Person(45,"Ginger"));
people.add(new Person(66,"Elsa"));
// Iterate over the list (one person at a time)
for (Person person : people) {
if (person.age > 60) {
System.out.println("Old person: " + person.name);
}
}
}
}
一般形式是:
for (Person person : people) {
...
}
代替:
for (int i = 0; i < people.size(); i++) {
Person person = people.get(i);
...
}
通常建议使用for-each,因为它更简洁.但是,如果您需要知道必须使用的项目的索引号原始for循环或增加for-each内的计数器.