当我需要在内部类中设置布尔标志时,我的Java代码中经常出现这种情况.不可能使用原始布尔类型,因为内部类只能使用外部的最终变量,所以我使用这样的模式:
// 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 ..............
Run Code Online (Sandbox Code Playgroud)
最终数组的模式而不是非最终变量的效果很好,除了它看起来不够漂亮.有人知道Java中更好的模式吗?