Java自动增量id

时间:2014-06-19 11:46:40

标签: java

我正在用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; 
  }
}

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

4 个答案:

答案 0 :(得分:21)

试试这个:     

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(); 
}

答案 1 :(得分:1)

使用以下内容

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;
}

}

请使用以下内容进行测试

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());
    }
}

}

答案 2 :(得分:0)

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; 
    }
}

您的代码可以使用,但如果点击Integer.MAX_VALUE,则可能会遇到一些问题。

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

答案 3 :(得分:-1)

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;
        } 
}
相关问题