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

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

问题描述

基于这个问题增加变量名?

我有一个数组列表peopleHolder",其中包含各种person"对象.我想基于 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;如何通过数组列表调用这些方法?我想要为每个对象设置值的方法.我看过这个答案: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 命名约定 并使用驼峰式风格.类/接口/枚举应以大写字母开头,如 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天全站免登陆