Dmitrii Bundin Dmitrii Bundin - 1 year ago 57
Java Question

Is there a way/workaround on incrementing ints in java8

I have the following method which performs a tree traversal and does some actions:

public int method(){
int retVal;
Tree t;
//initialization of t
t.accept(() -> ++retVal)); //error, variable is not
//effectively final
return retVal;


public interface Visitor{
public void visitNode();

public interface Tree{
* Traverses this tree and perform some action in each node
public void accept(Visitor v);

//other methods omitted

Is there a way to workaround this?

Answer Source

There aren't any that don't involve passing in an object instead of a local variable. However, you can do any of the following:

  1. Use an AtomicInteger
  2. Use an int[1]
  3. (if appropriate) Move the int to be an instance field
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download