Java,通过arraylist调用对象方法 [英] Java, call object methods through arraylist

查看:333
本文介绍了Java,通过arraylist调用对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此问题增加变量名?

我有一个数组列表"peopleHolder",其中包含各种人"对象. 我想基于for循环自动创建人"对象. 我做了以下

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调用此类方法? 我想要为每个对象设置值的方法. 我已经看过以下答案: Java-的调用方法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++);
}


顺便说一句,您应该坚持 Java命名约定,并使用camelCase样式.类/接口/枚举应以大写字母开头,例如Person,变量/方法名称的第一个标记应以小写字母开头,而其他的则以大写字母开头,例如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,通过arraylist调用对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆