for循环中的最终计数器? [英] A final counter in a for loop?
问题描述
我有这段代码:
List<Runnable> r = new ArrayList<>();
for(int i = 0; i < 10; i++) {
r.add(new Runnable() {
@Override
public void run() {
System.out.println(i);
}
});
}
显然无法编译,因为 i
需要最终才能在匿名类中使用。但我不能把它作为最终决定,因为事实并非如此。你会怎么做?一个解决方案是复制它,但我认为可能有更好的方法:
It obviously does not compile because i
would need to be final to be used in the anonymous class. But I can't make it final because it is not. What would you do? A solution is to duplicate it but I thought there might be a better way:
List<Runnable> r = new ArrayList<>();
for(int i = 0; i < 10; i++) {
final int i_final = i;
r.add(new Runnable() {
@Override
public void run() {
System.out.println(i_final);
}
});
}
编辑只是为了说清楚,我用过为了这个例子,这里有一个Runnable,问题实际上是关于匿名类,这可能是其他任何东西。
EDIT just to make it clear, I used a Runnable here for the sake of the example, the question is really about anonymous classes, which could be anything else.
推荐答案
我认为你的解决方案是最简单的方法。
I think your solution is the simplest way.
另一种选择是将内部类的创建重构为一个为你做的工厂函数,然后你的循环本身可以干得像:
Another option would be to refactor the creation of the inner class into a factory function that does it for you, then your loop itself could be something clean like:
List<Runnable> r = new ArrayList<>();
for(int i = 0; i < 10; i++) {
r.add(generateRunnablePrinter(i));
}
工厂函数可以声明最终参数:
And the factory function could just declare a final parameter:
private Runnable generateRunnablePrinter(final int value) {
return new Runnable() {
public void run() {
System.out.println(value);
}
};
}
我更喜欢这种重构方法,因为它保持代码更清晰,相对自我描述并且还隐藏了所有内部类管道。
I prefer this refactored approach because it keeps the code cleaner, is relatively self descriptive and also hides away all the inner class plumbing.
随机离题:如果你认为匿名内部类等同于闭包,那么 generateRunnablePrinter
实际上是一个更高阶的函数。谁说你不能用Java做函数式编程: - )
Random digression: if you consider anonymous inner classes to be equivalent to closures, then generateRunnablePrinter
is effectively a higher order function. Who said you can't do functional programming in Java :-)
这篇关于for循环中的最终计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!