且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java,通过arraylist调用对象方法

更新时间:2023-11-16 18:41:22

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

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.