简体   繁体   中英

Will Java notice when a loop won't change anything, or should I use break statement?

I would like to determine whether some element of String-List has some other String as a substring. My approach was something like

//...
boolean found = false;
for (String elem : myList) {
    if (elem.contains(someString)) {
        found = true;
        break;  // <-- necessary?
    }
}
if (found) {
    // do something
}

My Question is: is the break statement useful here? Intuitively it seems like omitting it would cause unnecessary work, since I am only interested in finding out whether the string is contained as a substring at least once.

However, a clever compiler could notice that after found has been set to true, the state of the program cannot change any more. Will the Java compiler or the JVM recognize this?

You're absolutely right. The break statement doesn't change the semantics of the algorithm (nor the complexity) but avoids doing unnecessary work once an element has been found.

(The JVM will most likely not discover that found never changes from true to false and break the loop in advance.)

I usually put this type of snippet in a method though, and use return statements as follows:

for (String elem : myList)
    if (elem.contains(someString))
        return true;
return false;

If you happen to be using Java 8, there's a better way though:

boolean found = myList.stream().anyMatch(s -> s.contains(someString));

Don't count on the compiler to break from the loop for you.

If you wish to avoid the break statement and still not do unnecessary work, you can re-write the loop this way :

boolean found = false;
for (int i = 0; i < myList.size() && !found; i++) {
    if (myList.get(i).contains(someString)) {
        found = true;
    }
}
if (found) {
    // do something
}

Or you can use a while loop.

I would use a while instead of a for loop:

//...
boolean found = false;
int i = 0;
while (i < myList.size() && !found) {
  String elem = myList.get(i)
    if (elem.contains(someString)) {
        found = true;
    }
    i++;
}
if (found) {
    // do something
}

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