java retain information in recursive function

后端 未结 8 1992
滥情空心
滥情空心 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: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.

提交回复
热议问题