'for' loop replaceable with 'foreach'
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
people.get(i) retrun an object of class People.
You can not compare a object with a number in if statement.
EDIT
How to iterate Arraylist
1)
for (int i = 0; i < people.size(); i++) {
if(people.get(i).getAvalue() > 60.0 ){//your code}
}
2)
for(People p: people){
if(p.getAvalue()>60.0){//you code}
}