2014-06-19 161 views
-4

我做一些編碼在Java中,但它不工作:的Java自動遞增ID

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。

+0

你已經這樣做了,順便說一下,請刪除左右'字符串逗號title' –

+0

是我的代碼罰款 –

+0

如果要創建多個作業對象,然後跟蹤JOB_ID的類之外(給你job_1,job_2等) – Kyte

回答

15

試試這個:

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

+1爲AtmicInteger(多線程沒有提到,但它總是很好是Threadsafe) –

+0

哪個最終?最終的AtomicInteger?這意味着一旦計數變量被初始化,它就不能被改變。 –

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

+0

謝謝,沒有看到 –

0

使用下,

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

}