问题描述
根据这个问题
我有一个arraylist'peopleHolder',它拥有各种人物物品。
我想基于for循环自动创建'person'对象。
我做了以下
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());
我想调用person类中的方法。例如person.setAge;
如何通过arraylist调用此类方法?
我想要为每个对象设置值的方法。
我看过这个答案:
但我认为解决方案依赖于调用静态方法,我希望在存储对象值时让对象特定于该对象。
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
}
或使用增强型for循环
or using enhanced for loop
int i=0;
for (person p: peopleHolder){
p.setName("newName" + i++);
}
BTW你应该坚持并使用camelCase样式。类/接口/枚举应以大写字母开头,如 Person
,变量/方法名称的第一个标记应以小写字母开头,而其他大写字母则以<$开头,如 c $ c> peopleHolder
。
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
.
这篇关于Java,调用对象方法,ar arylylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!