简体   繁体   中英

What keywords should I use in a for-loop when using if-statements?

Let's assume that we have a for-loop that will loop through a collection or array of Strings. In that case, I am searching for a specific keyword (ex. hey) here's how I usually achieve that:

for (String result : strings)
{
    if (result == "hey")
    {
        // Do something with that.
        break;
    }
}

Now, the question arises from that code snippet is, should I place a keyword (return or break) when the if-statement returns true so the loop will not continue? If not, what will happen and what's the correct way of going about it.

Edit: What happens when you use break and return? What's the difference?

Let's put your code inside a method:

private void foo() 
{
    for (String result : strings)
    {
        if (result.equals("hey"))
        {
            // Do something with that.
            break;
        }
    }
    bar();
}

If you use break; , the loop will terminate and bar will be reached. If you use return , the method will terminate and bar won't be executed.

Note that comparing strings should be done using equals , == compares references and not content.

If you know the word can only be found once you can surely place an break; statement so the loop won't continue after finding the match.

If you can have more than one match and you want the if block to be executed for each of those matches you should NOT put the break statement since it will stop the execution of the loop after the first match is found.

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