How to implement int in/out params in java

前端 未结 6 2089

Apologies for asking such a primitive question.

I wrote a function which took one parameter; this parameter was supposed to be an in/out parameter.

After d

6条回答
  •  甜味超标
    2020-12-21 12:47

    Answer 1:

    One approach would be to pass in an AtomicInteger, which is mutable.

    boolean getNextFoo(AtomicInteger foo) {
      foo.set(foo.get() + 1);
      return true;
    }
    

    Answer 2:

    The statement: currentFoo = currentFoo + 1 is not modifying the object; it is creating a new Integer instance and reassigning the local reference to point to it.

    When you exit from the method the local reference is "lost" (i.e. it goes out of scope) and hence reassigning it has no effect outside of the method.

提交回复
热议问题