Java - 返回值是否会破坏循环?

Java - Does returning a value break a loop?(Java - 返回值是否会破坏循环?)

本文介绍了Java - 返回值是否会破坏循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些基本上遵循以下格式的代码:

I'm writing some code that basically follows the following format:

public static boolean isIncluded(E element) {
    Node<E> c = head;
    while (c != null) {
        if (cursor.getElement().equals(element)) {
            return true;
        }
        c = c.getNext();
    }
    return false;
}

代码将在节点列表中搜索元素.但是,我的问题是,如果 while 循环确实找到了 if 语句说它应该返回 true 的元素,它会简单地返回 true 并中断循环吗?此外,如果它确实打破了循环,它会继续执行该方法并仍然返回false,还是一旦返回值,该方法是否完成?

The code will search for an element in a list of nodes. However, my question is that if the while loop does find the element where the if-statement says it should return true, will it simply return true and break the loop? Furthermore, if it does then break the loop will it then carry on through the method and still return false, or is the method completed once a value is returned?

谢谢

推荐答案

是*

是的,通常(在你的情况下)它确实会跳出循环并从方法返回.

Yes*

Yes, usually (and in your case) it does break out of the loop and returns from the method.

一个例外是,如果循环内有一个 finally 块并围绕着 return 语句,那么 finally 块中的代码将在方法返回之前执行.finally 块可能不会终止——例如它可能包含另一个循环或调用一个永远不会返回的方法.在这种情况下,您永远不会退出循环或方法.

One exception is that if there is a finally block inside the loop and surrounding the return statement then the code in the finally block will be executed before the method returns. The finally block might not terminate - for example it could contain another loop or call a method that never returns. In this case you wouldn't ever exit the loop or the method.

while (true)
{
    try
    {
        return;  // This return technically speaking doesn't exit the loop.
    }
    finally
    {
        while (true) {}  // Instead it gets stuck here.
    }
}

这篇关于Java - 返回值是否会破坏循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java - 返回值是否会破坏循环?