加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:46:06 所属栏目:Java 来源:网络整理
导读:我的代码是: ArrayListPeople 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 repl
我的代码是:
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内的计数器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读