java retain information in recursive function

后端 未结 8 1948
滥情空心
滥情空心 2020-12-29 09:05

Is it possible to retain information via a helper function with java, without using static variables.

For example,

public void foo(){
    int v = 0;
         


        
相关标签:
8条回答
  • 2020-12-29 09:44

    Why not make it an instance variable(not necessarily static)...??

    public class Recursive {
        int v = 0;
        public void foo(){
    
            fooHelper(2);
            System.out.println(v);
        }
    
        public void fooHelper(int depth){
            v++;
            if(depth-1!=0)//Added this because I was getting an StackOverflowError
            fooHelper(depth-1);
        }
    
        public static void main(String[] args) {
            Recursive r = new Recursive();
            r.foo();
        }
    }
    
    0 讨论(0)
  • 2020-12-29 09:46

    Because the variable v is of primitive type, changes made to it will not be visible outside the function scope. You could declare the variable v inside a class, say State and pass the state object into the recursive function to get the required effect.

    public void foo(){
        State state = new State();
        fooHelper(state, 2);
    }
    
    public void fooHelper(State state, int depth){
        state.v++;
        fooHelper(state, depth-1);
    }
    
    class State {
        int v;
    }
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题