我正在尝试创建生成唯一ID的方法。由于最终变量,我不能使用“return id ++”。还有其他选择吗?
public class Job {
private final long id;
private final int difficulty;
private final String owner;
public Job(int difficulty, String owner) {
this.id = nextId();
this.difficulty= difficulty;
this.owner= owner;
}
public long nextId(){
return id;
}
我也试过java.util.UUID。可以使用最终变量生成唯一ID吗?
private final String id;
...
public String nextId(){
id = UUID.randomUUID().toString();
return id;
我真的很感激任何帮助
答案 0 :(得分:1)
你需要两个变量:一个是静态的,它计算已经给出的ID,另一个是最后一个保存每个对象的ID。
public class Job {
private static long nextId = 0L;
private final long id;
private final int difficulty;
private final String owner;
public Job(int difficulty, String owner) {
this.id = nextId++;
this.difficulty = difficulty;
this.owner = owner;
}
// ...
}
如果这也需要在多线程环境中工作,则必须使用同步或原子操作(例如,AtomicLong
):
public class Job {
private static AtomicLong nextId = new AtomicLong();
private final long id;
private final int difficulty;
private final String owner;
public Job(int difficulty, String owner) {
this.id = nextId.getAndIncrement();
this.difficulty = difficulty;
this.owner = owner;
}
// ...
}