问题描述
当我需要在内部类中设置布尔标志时,我的Java代码经常出现这种情况。不可能使用原始布尔类型,因为内部类只能使用外部的最终变量,所以我使用这样的模式:
I often have a situation in my Java code when I need to set a boolean flag inside an inner class. It is not possible to use primitive boolean type for that, because inner class could only work with final variables from outside, so I use pattern like this:
// class from gnu.trove is not of big importance, just to have an example
private final TIntIntHashMap team = new TIntIntHashMap();
// ....... code ............
final boolean[] flag = new boolean[]{false};
team.forEachValue(new TIntProcedure() {
@Override
public boolean execute(int score) {
if(score >= VICTORY_SCORE) {
flag[0] = true;
}
return true; // to continue iteration over hash map values
}
});
// ....... code ..............
最终数组的模式而不是非最终变量的效果很好,除非它看起来不够漂亮。有人知道Java中更好的模式吗?
The pattern of final array instead of non-final variable works well, except it is not look beautiful enough to me. Does someone know better pattern in Java ?
推荐答案
在某些情况下,这是最好的模式。
There are situations where this is the best pattern.
当我找到匹配项时,我建议的唯一改进是 return false
。
The only improvement I can suggest is return false
when you have found a match.
这篇关于最终数组的模式而不是内部类中boolean标志的非final变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!