4

I would like to minimize the scope of arr to a do ... while loop, so it can be destroyed once the loop is exited.

If I declare arr within the do while loop, I get the error:

symbol cannot be found

I can declare it right before the cycle, but then I keep bloated arr in memory even though I don't need it any more.

//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);

What is the correct way to deal with this situation?

JavaHopper
  • 5,567
  • 1
  • 19
  • 27
sixtytrees
  • 1,156
  • 1
  • 10
  • 25

5 Answers5

6

You have:

  • An initial state
  • A terminating state
  • An iterative operation

So you have everything needed to use a for loop (albeit without a body):

for (int[] arr = {0}; arr.length < 9999; arr = evolve(arr));

Another solution, but nowhere near as neat, is to add this after the loop:

arr = null;

which still allows the allocated memory to be garbage collected and has a similar practical effect to restricting scope. Sometimes you need this approach if you can't refactor the code another way.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

You have a couple of ways. You can declare boolean token outside of a cicle and check against it. You can encapsulate the whole thing in a method that ends right after do while.

2

@Bohemian's solution is elegant.

But, if you still wan't to achieve this using do.. while, then following solution should work

    int l = 9999;
    do {
        int[] arr = { 0 }; // causes "cannot find symbol" on `while` line
        arr = evolve(arr); // modifies array, saves relevant results elsewhere
        l = arr.length;
    } while (l < 9999);
JavaHopper
  • 5,567
  • 1
  • 19
  • 27
2

You could also define the array outside the do-while loop and wrap the whole thing in a small method. The array will then be garbage collected when the method ends. This also helps to structure your code.

martinhh
  • 336
  • 2
  • 10
1

Yet another option - although arguably not better than any of those already mentioned - would be to wrap it into a block:

{
    int[] arr = {0}; // this works, but the scope is outside the loop
    do {
        int[] arr = {0};
        arr = evolve(arr); // modifies array, saves relevant results elsewhere
    } while (arr.length < 9999);
}

I'd prefer @martinhh's solution though - just extract it to a method with a meaningful name.

The body-less for loop is fine, too - but it would probably be a good idea to leave a comment there that it was indeed intentional to omit the body - things like that tend to get highlighted by static analysis tools and may cause some confusion.

Hulk
  • 6,399
  • 1
  • 30
  • 52