切换布尔值,但只有一次? (Java)的

时间:2011-09-02 08:54:42

标签: java boolean toggle

每隔一段时间就需要在循环中只存储一次布尔值(记录它已从false更改为true或反之亦然),同时执行循环到结束但不再关心更改在布尔值中。例如:


    public static boolean dbDelete(Collection argObjectCollectionToDelete) {
        boolean result = true;
        for (Object object : argObjectCollectionToDelete) {
            boolean dbDelete = dbDelete(object);
            if (!dbDelete) {
                result = false;
            }
        }
        return result;
    }

是否有某种方法可以执行相应的代码


if (!dbDelete) {
    result = false;
}


if (!dbDelete && !result) {
    result = false;
}

以更优雅的方式,最好是一行?

4 个答案:

答案 0 :(得分:8)

怎么样:

result &= dbDelete(object);

这相当于:

result = result & dbDelete(object);

只有当result 以前为真且dbDelete返回true时才会出现这种情况。

答案 1 :(得分:1)

if (!dbDelete(object)) {
    result = false;
}

答案 2 :(得分:1)

result = dbDelete(object)?结果:错误;

答案 3 :(得分:1)

尝试在变量名称中添加更多含义 - 这会使事情变得更容易。

public static boolean dbDelete(Collection argObjectCollectionToDelete) {
    boolean completedSuccessfully = true;
    for (Object object : argObjectCollectionToDelete) {
        boolean dbDelete = dbDelete(object);
        if (completedSuccessfully && !dbDelete) {  //won't change anymore after failure
            completedSuccessfully = false;
        }
    }
    return completedSuccessfully;
}