Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggling boolean value, but just once? (java)

Every now and then there is a need to store a boolean value only once (to record that it has changed from false to true or vice versa) in a loop, while executing the loop to the end but not caring anymore about changes in the boolean value. Example:


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

Is there some way to execute the equivalent of the code


if (!dbDelete) {
    result = false;
}

or


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

in a more elegant way, preferrably in one line?

like image 223
simon Avatar asked Dec 16 '22 09:12

simon


1 Answers

How about:

result &= dbDelete(object);

This is equivalent to:

result = result & dbDelete(object);

So it will only be true if result was previously true and dbDelete returned true.

like image 53
Jon Skeet Avatar answered Dec 23 '22 14:12

Jon Skeet