每当创建新对象时生成唯一 int



我想创建一个类:

class Student {
private static int id;
}  

每次创建来自Student的对象时,它都会为该学生分配一个唯一的 6 位 ID。

我在Stack Overflow上找到的其他相关问题并没有那么有帮助。

您可以使用依赖于学生类中static int字段的static方法。

如果您在构造函数调用中Student竞争条件:

public class Student {
    private static int currentId = 0;
    private static final int MAX_VAUE_ACCEPTED = 999999;
    private static Object lock = new Object();
    private static int getNewId() {
       synchronized(lock){
          if (currentId > MAX_VAUE_ACCEPTED) {
            // handling the problem because you is over 6 digits
          }
        currentId++;    
        return currentId;
       }
    }
    ...
    private int id;
    public Student(){
      this.id = getNewId();
    }
}

如果您没有任何竞争条件,则它是同一件事,但没有同步。

作为旁注,如果您使用数值来存储信息,如果您希望在所有情况下都以 6 位数字表示,则应转换为 String 以呈现 id。
因为例如000001不是你从数字中自然得到的表示。你宁愿:1.
如果需要,应该有一个进行转换以呈现 id 的方法。

您可以定义一个具有getID方法的ID类,以便在每次调用时返回新的 6 位 id:

class ID {
    private int id = 0;
    private final int max;
    private final String pattern;
    public ID(int digits) {
        this.max = (int) Math.pow(10, (digits));
        this.pattern = "%0" + digits + "d";
    }
    public synchronized String getID() {
        if(!(id < max)) throw new IllegalStateException("Too many IDs");
        return String.format(pattern, id++);
    }
}

(出于格式原因,在此处使用 String,您无需以任何方式使用 id 进行计算。

然后在Student类中,您可以简单地创建一个static ID,并在需要新 id 时调用getID

class Student {
    private static final ID idFactory = new ID(6);
    private final String id = idFactory.getId(); // will always get called for new Student
    ...
}

但是,如果对Student对象进行垃圾回收,则该对象的 Id 将不再可用。您也可以实现它,但这在您的情况下可能就足够了。

最新更新