我的代码是:
ArrayList<People> people = new ArrayList<>();
// people.add(...);
// people.add(...);
for (int i = 0; i < people.size(); i++) {
if (people.get(i) > 60.0)
System.out.println(people.get(i).toString());
}
我收到以下警告:
'for' loop replaceable with 'foreach'
我应该如何使用 foreach 修改循环?
谢谢。
最佳答案
名为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<Person> 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);
}
}
}
}
您还可以阅读 Oracle Java documentation about for-each loops .
一般形式是:
for (Person person : people) {
...
}
代替:
for (int i = 0; i < people.size(); i++) {
Person person = people.get(i);
...
}
通常推荐使用 for-each,因为它更简洁。 但是,如果您需要知道您必须使用的项目的索引号 原始的 for 循环或在 for-each 中增加一个计数器。
关于java - 'for' 循环可替换为 'foreach',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24811229/