我有以下代码,有没有一种很好的方法来计算State enum中的数字?
我想将StateHolders的函数移动到State枚举,但我不知道如何将起始编号与结束编号对应。
public enum State{
START("start"),
END("end");
public String msg;
private State(String msg){
this.msg = msg;
}
}
public class StateHolder{
private static AtomicInteger counter = new AtomicInteger();
private int current;
public String start(){
current = counter.getAndIncrement();
return State.START.msg + " " + current;
}
public String end(){
return State.END.msg + " " + current;
}
}
public static void main(String[] args){
StateHolder sh1 = new StateHolder();
StateHolder sh2 = new StateHolder();
System.out.println(sh1.start); // start 0
System.out.println(sh2.start); // start 1
System.out.println(sh1.end); // end 0
System.out.println(sh2.end); // end 1
}
答案 0 :(得分:0)
这个怎么样:
public enum State {
...
private static AtomicInteger counter = new AtomicInteger();
public AtomicInteger counter() {
return counter;
}
...
}
public class StateHolder {
private int current;
public String start() {
current = State.START.counter().getAndIncrement();
return State.START.msg + " " + current;
}
...
}