Java ArrayList


I have a question. Does anyone know how to retrieve an element from an object that has been put into an ArrayList?

I can create an object say Person with get and set values for name (String) and age (Int)

Then add the object to array list

ArrayList people = new ArrayList();
Person person = new Person(“Karen”, 25);

… but how to I get and print out just the age from the ArrayList (or if I were to create and add multiple People person to the list?

Thanks, here is one way (sorry, I figured it out)

  1. Create a simple class People (String name, int age)
a. Create several objects from class People
b. Add each one to an ArrayList as you create each one
c. Use the .get method from class ArrayList to obtain each object from ArrayList and reassign to class People.
d. Use the methods from People to obtain the information you require.

Hope that helps!

public class People {
	private String name;
	private int age;

	public People() {
		this("", 0);

	public People(String name, int age) { 

	public void setName(String name) { = name;

	public void setAge(int age) {
		this.age = age;

	public String getName() {
	       return name;

	public int getAge() {
		return age;

	public String toString() {
		return String.format("The name: %s the age: %d", name, age);

}//end class People


mport java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class TestPeople {
        public static void main(String[] args) {

                List<People> persons = new ArrayList<People>();

                People people = new People("karen", 14);
                People people0 = persons.get(0);
                System.out.printf("%s %d%n", people0.getName(), people0.getAge());

                people = new People("Susie", 12);
                People people1 = persons.get(1);
                System.out.printf("%s %d%n", people1.getName(), people1.getAge());

                people = new People("Marie", 14);
                People people2 = persons.get(2);
                System.out.printf("%s %d%n", people2.getName(), people2.getAge());
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.