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:
<
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.
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");
}
}
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"