gpt4 book ai didi

java - 迭代对象列表并为每个对象运行一个函数 - Java

转载 作者:行者123 更新时间:2023-12-01 19:51:18 26 4
gpt4 key购买 nike

我想知道如何为数组(或其他列表类型)中的每个对象运行特定函数的最简单方法

我的目标是能够创建一个对象列表,并让每个对象在通过迭代器时运行特定的函数。

我在数组列表上尝试了 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/

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