java 一旦满足条件就跳过 if 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32238127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:52:25  来源:igfitidea点击:

Skip if-statement once condition is met

javaloops

提问by Eric Guan

This question comes from my OCD-ish nature. Say i have this piece of code.

这个问题来自我的强迫症性质。说我有这段代码。

boolean executed = false;
for(Object o : Collection){
    if((o fulfills condition) && executed  == false){
        //do something
        executed  = true;
    } 
    //other code
}

If the specification only requires that the if statement executes once, is there a better way to skip checkingthe if conditional than setting executedto true? It bothers me that the loop needs to check the if conditional every single loop iteration, after the if statement has already been executed.

如果规范只要求 if 语句执行一次,是否有比设置为 true更好的方法来跳过检查if 条件executed?让我感到困扰的是,在 if 语句已经执行之后,循环需要在每次循环迭代中检查 if 条件。

The point of the executed boolean is to prevent the if statement from executing again. I'm not sure this is possible, but i want to take it one step further, and skip checking the if conditional once executedis true.

执行布尔值的目的是防止 if 语句再次执行。我不确定这是否可行,但我想更进一步,跳过检查 if conditional once executedis true

EDIT: I still need to finish the loop after the condition is met.

编辑:我仍然需要在满足条件后完成循环。

回答by Makoto

Not really; you're stuck checking that conditional each time with this code flow. There are ways to make it less expensive, though.

并不真地; 每次使用此代码流时,您都必须检查该条件。不过,有一些方法可以降低成本。

I would advise against using continue, since it will cause you to check the conditional repeatedly and thenfall through, which probably isn't what you want.

我建议不要使用continue,因为它会导致您反复检查条件然后失败,这可能不是您想要的。

The simplest thing to do may be to reorder the boolean AND statement.

最简单的方法可能是重新排序布尔 AND 语句。

boolean executed = false;
for(Object o : Collection){
    if(!executed && (o fulfills condition)){
        executed  = true;
    } 
    //other code
}

Due to Java's short-circuit nature, you will only ever check !executed, and on its second and future runs, that will evaluate to false, thus "skipping" the conditional check.

由于 Java 的短路特性,您只会检查!executed,并且在第二次和以后的运行中,它将评估为false,从而“跳过”条件检查。

回答by tt_emrah

i would go with a different way, like below:

我会采用不同的方式,如下所示:

int i = 0;
for ( ; i<collection.size() ; i++)
{
    Object o = collection.get(i);
    if (o fulfills condition)
    {
        // do what you gotta do and then
        break;
    }
    doSomethingElse(o); // define a private method for whatever is done here
}
for ( ; i<collection.size() ; i++)
{
    doSomethingElse(collection.get(i));
}

回答by Andreas

Assuming you still want "other code" to keep running, and that the condition test mightbe slow, flip the tests and the boolean:

假设您仍然希望“其他代码”继续运行,并且条件测试可能很慢,请翻转测试和布尔值:

boolean doTest = true;
for(Object o : Collection){
    if (doTest && (o fulfills condition)) {
        doTest = false;
    }
    //other code
}

This eliminates the negative, and the &&operator prevent the condition from being evaluated once doTestis false.

这消除了否定,并且&&运算符防止条件被评估一次doTestis false

回答by Prashant

Not knowing the context, the only improvement I would suggest is to check for executed first-

不知道的情况下,唯一的改进,我建议是检查执行第一-

boolean executed = false;
for(Object o : Collection){
    if(executed  == false && (o fulfills condition) ){
        //do something
        executed  = true;
    } 
    //other code
}

This will have the least side-effects. Otherwise, I don't know how to improve your solution since you say "other-code" still need to execute. Hope this helps.

这将产生最少的副作用。否则,我不知道如何改进您的解决方案,因为您说“其他代码”仍然需要执行。希望这可以帮助。

回答by Parker Hoyes

In order to loop through a list and perform a task only the first time a condition is met, and not test the condition afterwards, you can make use of the short-circuit nature of Java's andoperator. See the following code:

为了循环遍历列表并仅在第一次满足条件时执行任务,然后不测试条件,您可以利用 Javaand运算符的短路特性。请参阅以下代码:

boolean performed = false;
for(Object o : Collection){
    if(!performed && o fulfills condition){
        //do something
        performed  = true;
    } 
    //other code
}

After the task is performed, the performedflag will be set to true. When Java realizes the first operand (the condition before the &&) evaluates to true, it doesn't bother calculating o fulfills condition. This is called short-circuiting. This is useful when the second operand (o fulfills condition) is an expensive calculation that you want to avoid performing if it's not necessary.

任务执行后,该performed标志将设置为真。当 Java 实现第一个操作数( 之前的条件&&)的计算结果为真时,它不会计算o fulfills condition。这称为短路。这在第二个操作数 ( o fulfills condition) 是一个昂贵的计算时很有用,如果不需要,您希望避免执行。