H J
H J

Reputation: 369

Java, call object methods through arraylist

Based on this question Increment variable names?

I have an arraylist 'peopleHolder' which holds various 'person' objects. I would like to automatically create 'person' objects based on a for loop. I did the following

    peopleHolder.add(new person());

I would like to call methods from the person class. for example person.setAge; How can I call such methods through an arraylist? I would like the method to set values for each object. I have looked at this answer: Java - calling methods of an object that is in ArrayList
But I think the solution depends on calling static method and I would like to have the method specific to the object as they store the objects value.

Upvotes: 6

Views: 70697

Answers (4)

Pshemo
Pshemo

Reputation: 124215

If you want to call some method at all objects from your list you need to iterate over them first and invoke method in each element. Lets say your list look like this

List<person> peopleHolder = new ArrayList<person>();
peopleHolder.add(new person());
peopleHolder.add(new person());

Now we have two persons in list and we want to set their names. We can do it like this

for (int i=0; i<list.size(); i++){
    list.get(i).setName("newName"+i);//this will set names in format newNameX
}

or using enhanced for loop

int i=0;
for (person p: peopleHolder){
    p.setName("newName" + i++);
}

BTW you should stick with Java Naming Conventions.

  • your types, so classes and interfaces (which includes enums, records, etc.) should starts with upper-case like class Person {..}, not class person {..}
  • your variables and methods should start with lower-case like peopleHolder.

Upvotes: 13

William Moffitt
William Moffitt

Reputation: 279

Following your code you could do this

ArrayList<Person> personHolder = new ArrayList<Person>();

for (int i = 0; i < 10; i++) {

    personHolder.add(new Person());

}

// If you want user input, do it in the loop below
for (Person p : personHolder) {

    p.setAge(30);

}

Upvotes: 1

nachokk
nachokk

Reputation: 14413

I have several person objects. I automatically create new person objects in a 'people' arrayList using a loop. I would like to access methods that define various characteristics of the objects( setAge, setHeight etc.) How can I access such methods for the objects I have created in my arraylist

In the same way as you create.

For every person in list you can iterate it

for(Person person : peopleHolder){
  person.setHeight(..);
  person.setAge(..)
}

For some index in the list, you can use get(int index) as your list is an arrayList then it's O(1).

 Person p = peopleHolder.get(someIndex); // where  0 <= someIndex < peopleHolder.size()
 p.setHeight(..);

Upvotes: 2

Crickcoder
Crickcoder

Reputation: 2155

Is this what you are looking for ?

for(person people: peopleHolder){
people.setAge(25);
}

Upvotes: 3

Related Questions