user1621585
user1621585

Reputation: 71

Automatic id generation

Any one have idea how to generate id starting from 1 so that the next object has 2 and so on?

I have trying the following but dose not work:

class students{

    private int id;
    private String name;

    public student(String name){
        this.id=id++;
        this.name
    }
}

Upvotes: 2

Views: 11122

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477040

You need a static class member to keep track of the last-used index. Be sure to also implement a copy constructor:

class students
{
    private static int next_id = 0;   // <-- static, class-wide counter

    private int id;                   // <-- per-object ID

    private String name;

    public students(String name)
    {
        this.id = ++students.next_id;
        this.name = name;

        // ...
    }

    public students(students rhs)
    {
        this.id = ++students.next_id;
        this.name = rhs.name;

        // ...
    }

    public static void reset_counter(int n)  // use with care!
    {
        students.next_id = n;
    }

    // ...
}

Update: As @JordanWhite suggest, you might like to make the static counter atomic, which means that it will be safe to use concurrently (i.e. in multiple threads at once). To that end, change the type to:

private static AtomicInteger next_id = new AtomicInteger(0);

The increment-and-read operation and the reset operation become:

this.id = students.next_id.incrementAndGet();  // like "++next_id"

students.next_id.set(n);                       // like "next_id = n"

Upvotes: 4

Mike Valenty
Mike Valenty

Reputation: 8981

Beware, using a static variable to keep track of your counter works in a very limited circumstance.

You can't run this code on more than one machine e.g. a web cluster if it's a web application. Also, the static variable is transient and will reset when you restart your application.

A common solution to generating a sequential id is to use a database. Most databases have a built-in way do this. For example, IDENTITY in SQL Server or AUTO_INCREMENT in MySQL.

Consider using a persistence framework like Hibernate and you can declare one of many proven strategies like identity, hilo or uuid some of which are sequential and some aren't. Some are generated by the application and some by the database but the trade-offs are well documented and you'll know what you're getting yourself into.

Upvotes: 4

Mark Yao
Mark Yao

Reputation: 408

you should chanage private int id; to private static int id; and id++ to ++id.

you can try:

class Students{
    private static int id;
    private String name;
    public Students(String name){
    this.id=++id; // this.id +=1;may be better 
    System.out.println(this.id);
    this.name = name;
   }
}

TestCode:

public class Test {
public static void main(String[] args) {
    Students s1 = new Students("Mark1");
    Students s2 = new Students("Mark2");
}

}

Upvotes: 0

Related Questions