java – ‘for’循环可替换为’foreach’

前端之家收集整理的这篇文章主要介绍了java – ‘for’循环可替换为’foreach’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的代码是:
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相关文章