假设我们只有一个带有int ID的简单对象Person来识别它.如何为Person的每个新实例提供新的ID值(+1),但是在该类Person的构造函数中?(我没有使用DB)
使用静态AtomicInteger:
final class Foo {
private static final AtomicInteger seed = new AtomicInteger();
private final int id;
public Foo() {
this.id = seed.incrementAndGet();
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参见此处:https://stackoverflow.com/a/4818753/17713
| 归档时间: |
|
| 查看次数: |
315 次 |
| 最近记录: |