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.
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.
for(People objPeople : people){
//Loop's code
}
Official documentation here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With