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 - 返回值是否会破坏循环?
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01