Java - Does returning a value break a loop?(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 - 返回值是否会破坏循环?
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01