Java自增id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24305830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:24:55  来源:igfitidea点击:

Java auto increment id

java

提问by Jot Dhaliwal

I am doing some coding in Java, but it doesn't work:

我正在用 Java 进行一些编码,但它不起作用:

public class job
{
   private static int count = 0; 
   private int jobID;
   private String name;
   private boolean isFilled;

   public Job(, String title, ){
      name = title;
      isFilled = false;
      jobID = ++count; 
  }
}

I need to auto-increment the Id when a new entry is created.

创建新条目时,我需要自动增加 Id。

采纳答案by win_wave

Try this:

尝试这个:

public class Job {
  private static final AtomicInteger count = new AtomicInteger(0); 
  private final int jobID;
  private final String name;

  private boolean isFilled;

  public Job(String title){
    name = title;
    isFilled = false;
    jobID = count.incrementAndGet(); 
}

回答by Programmer

public class job
{
    private static int jobID;
    private String name;
    private boolean isFilled;

    public Job(String title){
        name = title;
        isFilled = false;

        synchronized {
            jobID = jobID + 1;
        } 
}

回答by Christian Kuetbach

public class Job // Changed the classname to Job. Classes a written in CamelCasse Uppercase first in Java codeconvention
{
    private static int count = 0; 
    private int jobID;
    private String name;

    private boolean isFilled; // boolean defaults to false

    public Job(String title){ // Your code wan unable to compile here because of the ','
        name = title;
        isFilled = false;     // sets false to false
        jobID = ++count; 
    }
}

Your code will work, but you may get some problems, if you hit Integer.MAX_VALUE.

您的代码可以工作,但如果您点击 ,您可能会遇到一些问题Integer.MAX_VALUE

It may be a better soltion to choose long. Or If you only need a Unique Identifier UUID.randomUUID()

可能是更好的选择long。或者如果您只需要唯一标识符UUID.randomUUID()

回答by swgkg

Use the following,

使用以下,

public class TestIncrement {
private static int count = 0;
private int jobID;
private String name;

private boolean isFilled;

public TestIncrement(String title) {
    name = title;

    isFilled = false;
    setJobID(++count);
}

public int getJobID() {
    return jobID;
}

public void setJobID(int jobID) {
    this.jobID = jobID;
}

}

}

Please use following to test this

请使用以下来测试这个

public class Testing {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    for (int i = 0; i < 10; i++) {
        TestIncrement tst = new TestIncrement("a");
        System.out.println(tst.getJobID());
    }
}

}

}