Reply to comment

Using for each in Java in Iterating Arraylist

Tagged:  

The basic for loop in Java was extended to make iteration over arrays and other collections more convenient. This newer for statement is called the enhanced for or foreach.

Here's an example of using foreach to iterate Arraylist of type Person.

//Person.java
public class Person {
	
	private String firstName = null;
	private String lastName = null;	
	private int age = 0;
	
	public Person(String firstName, String lastName, 
			int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
	public String getFirstName() {
		return firstName;
	}
	
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	
	public String getLastName() {
		return lastName;
	}
	
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

}
//DisplayArrayList.java
import java.util.ArrayList;

public class DisplayArrayList {

	public static void main(String[] args){
		//declare generic ArrayList
		ArrayList<Person> list = new ArrayList<Person>();

		//add person to list
		list.add( new Person("Juan", "Cruz", 16) );
		list.add( new Person("Peter", "James", 14) );
		list.add( new Person("James", "Bond", 16) );
		list.add( new Person("JR", "Galia", 20) );
		list.add( new Person("Jack", "Bauer", 11) );

		
		//display unsorted
		System.out.println("\n\tFirst Name\tLast Name\tAge");
		for( Person p: list ){
			System.out.println("\t"+p.getFirstName() +"\t\t"
			 + p.getLastName() + "\t\t" +p.getAge());
		}
		
	}
}

Reply

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.