Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 878
H J Avatar asked Aug 26 '13 03:08

H J


1 Answers

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.
like image 186
Pshemo Avatar answered Oct 11 '22 23:10

Pshemo