Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'for' loop replaceable with 'foreach'

My code is:

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());
        }

And I get the following warning:

'for' loop replaceable with 'foreach'

How should I modify the loop using foreach?

Thanks.

like image 227
Mark Korzhov Avatar asked Jul 17 '14 18:07

Mark Korzhov


2 Answers

A list called people would normally contain Person objects.

Here's some example code that shows how to use a for-each loop:

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);
            }
        }
    }
}

You can also read the Oracle Java documentation about for-each loops.

The general form is:

for (Person person : people) {
    ...
}

Instead of:

for (int i = 0; i < people.size(); i++) { 
    Person person = people.get(i);
    ...
}

The for-each is usually recommended because it's terser. However, if you need to know the index number of the item you will have to use the original for loop or increment a counter inside the for-each.

like image 182
ᴇʟᴇvᴀтᴇ Avatar answered Sep 27 '22 23:09

ᴇʟᴇvᴀтᴇ


for(People objPeople : people){
//Loop's code
}

Official documentation here

like image 21
Vaishak Suresh Avatar answered Sep 27 '22 21:09

Vaishak Suresh