Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java auto increment id [closed]

Tags:

java

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

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.

like image 219
Jot Dhaliwal Avatar asked Jun 19 '14 11:06

Jot Dhaliwal


2 Answers

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(); 
}
like image 169
win_wave Avatar answered Oct 08 '22 00:10

win_wave


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

}

like image 39
swgkg Avatar answered Oct 07 '22 23:10

swgkg