Java ArrayList


#1

Hi

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);
people.add(person);

... 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?


#3

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

People.java
1. Create a simple class People (String name, int age)

TestPeople.java
2.
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) { 
 		setName(name);
		setAge(age);
	}

	public void setName(String name) {
		this.name = name;
	}

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

	public String getName() {
	       return name;
      	}

	public int getAge() {
		return age;
	}

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


}//end class People

i

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);
                persons.add(people);
                People people0 = persons.get(0);
                System.out.printf("%s %d%n", people0.getName(), people0.getAge());

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

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

#4

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