我想知道如何为数组(或其他列表类型)中的每个对象运行特定函数的最简单方法
我的目标是能够创建一个对象列表,并让每个对象在通过迭代器时运行特定的函数。
我在数组列表上尝试了 for 循环
for (int i = 0; i < testList.size(); i++)
{
this = textList.get(i);
this.exampleFunction();
}
但这给了我一个“预期变量”错误
最佳答案
假设您使用的是 Java 8+,并且您有 Collection<TypeInList>
您可以调用 Collection.stream()
并执行 forEach
关于这一点。就像,
testList.stream().forEach(TypeInList::function);
您当前的方法是尝试使用 this
做事那是不可能的。它可以像这样修复,
for (int i = 0; i < testList.size(); i++)
{
TypeInList that = testList.get(i); // this is a reserved word.
that.function();
}
或
for (TypeInList x : testList) {
x.function();
}
关于java - 迭代对象列表并为每个对象运行一个函数 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256083/