Java – ‘for’ loop can be replaced by ‘foreach’
•
Java
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()); }
I received the following warning:
How should I use foreach to modify loops?
thank you.
Solution
A list named people usually contains a person object
Here are some sample code showing how to use the 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 Oracle Java documentation about for each loops
The general form is:
for (Person person : people) { ... }
Substitute:
for (int i = 0; i < people.size(); i++) { Person person = people.get(i); ... }
For - each is generally recommended because it is more concise However, if you need to know the index number of the item you must use, the original for loop or increase the counter in for each
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码