简体   繁体   中英

How to check multible boolean values true or false in java>

I have 8 boolean values. I want to rollback when one or more of 8 booleans have false.

boolean flag = false;
        boolean flag1 = false;
        boolean flag2 = false;
        boolean flag3 = false;
        etc,,.

flag = dbCall...

here the flag value changes.

Here I have to check manually like

    if(flag == false && flag1 == false && ....){
      userTransaction = rollback;
    }else{
     userTransaction = commit;
    }

is there any simple way to check multple boolean values in java.

Your code have a bug initially.

if(flag = false && flag1 = false && ....){
  userTransaction = rollback;
}

= (assigning) is different than == (compare).

Next thing is with your current style you can reduce the code as

if(! flag || !flag1 ||  ....){
  userTransaction = rollback;
}

Because they are booleans you need not to check again with booleans.

Last thing I suggest is, where ever these variables are coming from , maintain a list and iterate over them to check all, with that way, you code related to checking remains constant even though n number of booleans you have.

how about the following?

if(flag  && flag1  && ....){
     userTransaction = commit;
  } else {
      userTransaction = rollback;
  }

I think this is the fastest way to handle this.

  1. Write your flags into an List or an Array

  2. test it like this

As List:

if(!myList.contains(false)) //all true;

As Array

if(!myArray.asList().contains(false)) //all true;

You can perform and operation on all values with BooleanUtils by Apache:

if (BooleanUtils.and(flag1, flag2, flag3, flag4)) {
    userTransaction = commit;
} else {
    userTransaction = rollback;
}

Or just do it usual way:

if (flag1 && flag2 && flag3 && flag4)) {
    userTransaction = commit;
} else {
    userTransaction = rollback;
}

If you don't need intermediate result, then you may try this:

boolean result = true;
boolean doRollback = true;
try {
  result = db.doSomething1() && result; // ? && true -> ?; 
  result = db.doSomething2() && result; // if result: false then ? && result -> false
  if (result) {userTransaction.commit(); doRollback = false;}
} finally {
  if (doRollback) userTransaction.rollback();
}

That would ensure that each db operations are executed ... and that result contains the final result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM