To loop through the elements of an ArrayList
of objects in Java, you can use a for
loop or the for-each
loop.
Here is an example of how you can use a for
loop to iterate through the elements of an ArrayList
and print their values:
List<Person> people = new ArrayList<>(); people.add(new Person("John", "Doe")); people.add(new Person("Jane", "Doe")); people.add(new Person("Bob", "Smith")); for (int i = 0; i < people.size(); i++) { Person person = people.get(i); System.out.println(person.getFirstName() + " " + person.getLastName()); }
This will print the first and last names of the Person
objects in the ArrayList
.
Here is an example of how you can use a for-each
loop to achieve the same result:
List<Person> people = new ArrayList<>(); people.add(new Person("John", "Doe")); people.add(new Person("Jane", "Doe")); people.add(new Person("Bob", "Smith")); for (Person person : people) { System.out.println(person.getFirstName() + " " + person.getLastName()); }
You can also use the Iterator
class to iterate through the elements of an ArrayList
, like this:
List<Person> people = new ArrayList<>(); people.add(new Person("John", "Doe")); people.add(new Person("Jane", "Doe")); people.add(new Person("Bob", "Smith")); ListIterator<Person> iter = people.listIterator(); while(iter.hasNext()){ Person person = iter.next(); System.out.println(person.getFirstName() + " " + person.getLastName()); }