six*_*ees 4 java scope loops initialization do-while
我想的范围减少arr到一个do ... while循环,所以一旦退出循环,可以销毁.
如果我宣布arr 内的do while循环,我得到的错误:
符号无法找到
我可以在循环之前声明它,但是arr即使我不再需要它,我仍然会在内存中保持膨胀.
//int[] arr = {0}; // this works, but the scope is outside the loop
do {
int[] arr = {0}; // causes "cannot find symbol" on `while` line
arr = evolve(arr); // modifies array, saves relevant results elsewhere
} while (arr.length < 9999);
Run Code Online (Sandbox Code Playgroud)
处理这种情况的正确方法是什么?
你有:
因此,您拥有使用for循环所需的一切(尽管没有正文):
for (int[] arr = {0}; arr.length < 9999; arr = evolve(arr));
Run Code Online (Sandbox Code Playgroud)
另一个解决方案,但不是很整洁,是在循环后添加这个:
arr = null;
Run Code Online (Sandbox Code Playgroud)
它仍然允许分配的内存被垃圾收集,并且具有与限制范围类似的实际效果.如果你不能以另一种方式重构代码,有时你需要这种方法.