在java8中增加整数有什么方法/解决方法吗
我使用以下方法执行树遍历并执行一些操作:在java8中增加整数有什么方法/解决方法吗,java,lambda,java-8,Java,Lambda,Java 8,我使用以下方法执行树遍历并执行一些操作: public int method(){ int retVal; Tree t; //initialization of t t.accept(() -> ++retVal)); //error, variable is not //effectively final return retVal; } 在哪里 有办法解决这个问题吗?没有任何方
public int method(){
int retVal;
Tree t;
//initialization of t
t.accept(() -> ++retVal)); //error, variable is not
//effectively final
return retVal;
}
在哪里
有办法解决这个问题吗?没有任何方法不涉及传入对象而不是局部变量。但是,您可以执行以下任一操作:
int[1]
int
移动为实例字段没有任何一种方法不涉及传入对象而不是局部变量。但是,您可以执行以下任一操作:
int[1]
int
移动为实例字段我建议创建一个可聚合的、命名良好的类
public final class CountVisitor implements Visitor {
private int count;
@Override
public void visitNode() {
this.count++;
}
public int getCount() {
return this.count;
}
}
然后像这样使用它:
public int method(){
CountVisitor counter;
Tree t;
t.accept(counter);
return counter.getCount();
}
如前所述,它是可重用的,名称有助于记录其用途。我建议创建一个可重用的、命名良好的类
public final class CountVisitor implements Visitor {
private int count;
@Override
public void visitNode() {
this.count++;
}
public int getCount() {
return this.count;
}
}
然后像这样使用它:
public int method(){
CountVisitor counter;
Tree t;
t.accept(counter);
return counter.getCount();
}
如前所述,它是可重用的,名称有助于记录其用途。当然;使用一个
AtomicInteger
或其他可变持有者。@LouisWasserman是的,我考虑过,但它不会引入一些不必要的同步通信量并导致执行CAS指令吗?是的。如果你担心这一点,那就使用其他可变的holder——即使是int[1]
也可以。@LouisWasserman实际上,明白了,Thanks很多。当然;使用一个AtomicInteger
或其他可变持有者。@LouisWasserman是的,我考虑过,但它不会引入一些不必要的同步通信量并导致执行CAS指令吗?是的。如果你担心这个问题,可以使用其他可变的holder——即使是int[1]
也可以。@LouisWasserman,事实上,明白了,Thanks很多。