[英]create unique id without using constructure and setters
class person {
private int id ;
private String name;
private boolean gender;
public person() {
}
public AtomicLong getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
}
I want to create unique id in this class without using constructors and setters.我想在不使用构造函数和 setter 的情况下在这个类中创建唯一的 id。
To construct a person
instance, the field initializer will be copied into the constructor.要构造一个
person
实例,字段初始值设定项将被复制到构造函数中。 Assuming that's okay, you could use an AtomicInteger
and something like,假设没问题,你可以使用
AtomicInteger
东西,
private static AtomicInteger ai = new AtomicInteger(0);
private int id = ai.incrementAndGet();
you could add:你可以添加:
private static int ID_GENERATOR = 0;
then, in the constructor, you will use:然后,在构造函数中,您将使用:
public person() {
id = ID_GENERATOR++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.