Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...