爪哇 - 是否返回一个值打破循环? [英] Java - Does returning a value break a loop?

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

问题描述

我在写一些code,基本上遵循以下格式:

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;
}

的code将搜索节点的列表的元素。不过,我的问题是,如果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.

一个例外是,如果有一个最后的循环中块和周围return语句然后在finally块中的code将在方法返回之前执行。 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.
    }
}

这篇关于爪哇 - 是否返回一个值打破循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆