我的代码是:
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内的计数器.