简体   繁体   English

如何在Java>中检查多重布尔值true或false

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

I have 8 boolean values. 我有8个布尔值。 I want to rollback when one or more of 8 booleans have false. 当8个布尔值中的一个或多个布尔值为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. 有没有简单的方法来检查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. 我建议的最后一件事是,无论这些变量来自何处,都要维护一个列表并遍历它们以进行全部检查,这样,即使您拥有n个布尔值,与检查相关的代码仍保持不变。

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: 您可以使用Apache的BooleanUtils对所有值执行and操作:

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. 这将确保每个db操作都已执行...并且该结果包含最终结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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