Search code examples
javarecursioncoding-styleintegerfinal

How to keep a "things done" count in a recursive algorithm in Java?


I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to handle multiple returned types.

I tried using an Integer type, declared outside the method and passed into the recursive method, but because it's final, recursive call increments are "forgotten" when I return. (Because the increment of the Integer value makes the passed-by-value object reference point at a new object)

Is there a way to get something similar to work which won't pollute my code?


Solution

  • Since you've already discovered the pseudo-mutable integer "hack," how about this option:

    Does it make sense for you to make a separate Parser class? If you do this, you can store the current state in a member variable. You probably need to think about how you're going to handle any thread safety issues, and it might be overkill for this particular application, but it might work for you.