Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 684
Andrew Harmel-Law Avatar asked Dec 30 '22 11:12

Andrew Harmel-Law


1 Answers

It's kind of a hack, but sometimes I use an AtomicInteger, which is mutable, to do things like this. I've also seen cases where an int[] of size 1 is passed in.

like image 170
Outlaw Programmer Avatar answered Jan 01 '23 23:01

Outlaw Programmer