gpt4 book ai didi

Java,通过arraylist调用对象方法

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:02 24 4
gpt4 key购买 nike

基于这个问题Increment variable names?

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

    peopleHolder.add(new person());

我想调用 person 类的方法。例如 person.setAge;如何通过数组列表调用此类方法?我想要为每个对象设置值的方法。我看过这个答案:Java - calling methods of an object that is in ArrayList
但我认为解决方案取决于调用静态方法,我希望在存储对象值时使用特定于对象的方法。

最佳答案

如果您想在列表中的所有对象上调用某些方法,您需要先遍历它们并在每个元素中调用方法。假设您的列表看起来像这样

List<person> peopleHolder = new ArrayList<person>();
peopleHolder.add(new person());
peopleHolder.add(new person());

现在列表中有两个人,我们要设置他们的名字。我们可以这样做

for (int i=0; i<list.size(); i++){
list.get(i).setName("newName"+i);//this will set names in format newNameX
}

或者使用增强的for循环

int i=0;
for (person p: peopleHolder){
p.setName("newName" + i++);
}

顺便说一句,你应该坚持使用 Java Naming Conventions .

  • 您的类型,因此类和接口(interface)(包括枚举、记录等)应该以大写开头,例如class Person {..},而不是类人{..}
  • 您的变量和方法应该以小写开头,例如peopleHolder

关于Java,通过arraylist调用对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18435992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com