java返回入for循环或外循环
今天,有人告诉我Java中return
关键字的错误用法。我编写了一个简单的for
循环,以验证数组中是否存在某些内容。假设array
是一个长度为n
的数组,这是我的代码:
for (int i = 0; i < array.length; ++i) {
if (array[i] == valueToFind) {
return true;
}
}
return false;
现在有人告诉我,这不是很好的编程,因为我在循环中使用return
语句,这会导致垃圾收集出现故障。因此,更好的代码应该是:
int i = 0;
while (i < array.length && array[i] != valueToFind) {
++i;
}
return i != array.length;
问题是,我无法正确解释为什么第一个for循环不是一个好的实践。谁能给我解释一下吗
# 1 楼答案
一些人认为一个方法应该有一个单一的出口点(例如,只有一个^{)。就我个人而言,我认为试图坚持这一规则会产生更难阅读的代码。在你的例子中,一旦你找到你要找的东西,立即返回,它很清楚,而且很有效
Quoting the C2 wiki:
# 2 楼答案
代码在这两种情况下都有效(即编译和执行)
我在Uni的一位讲师告诉我们,在任何循环中使用
continue
、return
语句是不可取的。这样做的原因是,在检查代码时,无法立即确定循环的整个长度是否会被执行,或者return
或continue
是否会生效有关示例,请参见Why is continue inside a loop a bad idea?
需要记住的关键点是,对于这样的简单场景,这并不重要(IMO),但是当您有复杂的逻辑来确定返回值时,如果您有一个而不是几个返回语句,那么代码“通常”更具可读性
关于垃圾收集,我不知道为什么这会成为一个问题
# 3 楼答案
那是一堆垃圾。方法内部的所有内容都将被清除,除非类或其他地方有其他对它的引用(这就是封装很重要的原因)。根据经验,通常最好只使用一个return语句,因为它更容易确定方法将退出的位置
就我个人而言,我会写:
# 4 楼答案
这是不正确的,并且建议你应该以一定程度的怀疑态度对待那个人的其他建议
“只有一个返回语句”(或者更一般地说,只有一个退出点)在需要自己管理所有资源的语言中是非常重要的,这样你就可以确保把所有清理代码放在一个地方
它在Java中的用处要小得多:只要知道应该返回(以及返回值应该是什么),就返回。这样的话,阅读起来就更简单了——你不必接受该方法的任何其他部分来计算出还会发生什么(除了
finally
块)# 5 楼答案
所有语言中都有提倡在任何函数中使用单一返回语句的方法。尽管在某些代码中不可能做到这一点,但有些人确实努力做到这一点,然而,这可能会使代码变得更复杂(比如在更多的代码行中),但另一方面,更容易理解(比如在逻辑流中)
这不会以任何方式扰乱垃圾收集
更好的方法是设置一个布尔值,如果你想听他的话
# 6 楼答案
因为GC没有问题。我更喜欢这个