H J H J - 6 months ago 42
Java Question

Java, call object methods thorugh 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.



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 and use camelCase style. Classes/interfaces/enums should starts with upper-case letter like Person, first token of variables/methods name should start with lower-case but others with upper-case like peopleHolder.