Let's say we just have a simple object Person with int ID which identifies it. How can I give new ID value (+1) for each new instance of Person but in constructor of that class Person? (I use no DB for this)
5 Answers
Use a static AtomicInteger:
final class Foo {
private static final AtomicInteger seed = new AtomicInteger();
private final int id;
public Foo() {
this.id = seed.incrementAndGet();
}
}
See here for more information: https://stackoverflow.com/a/4818753/17713
Comments
You could create a static variable for the current counter value, and assign that to the ID when created...
public class Person {
// same across all instances of this class
static int currentCounter = 0;
// only for this instance
int personId;
public Person(){
personId = currentCounter;
currentCounter++;
}
}
1 Comment
wattostudios
True. I guess its up to the author to choose the answer which is most appropriate for their context, although a thread-safe answer like @Mudu will allow for all contexts regardless. Thanks for your feedback.
use static variables; static variables aren't bound to class instances, rather to classes directly.
Example (in C#):
public class Person{
public static int Increment = 1;
public int ID;
public Person(){
this.ID = Increment;
Increment++;
}
}
This way all class instances will have unique ID-s (incremented by 1).
EDIT: This approach isn't thread-safe, see @Mudu's answer.
10 Comments
Jon Skeet
Except that's not thread-safe, nor is it a good idea to have public variables, nor is it following Java naming conventions.
Matthias Meid
Bear in mind that this is not thread-safe, but fine as long as you're not using multiple threads.
Sanjay T. Sharma
This solution doesn't take into consideration the threaded invocation of
Person constructor.Neil
@JonSkeet - in his defence he has stated it is a C# example, I think you could offer a Java answer yourself?
Jon Skeet
@Neil: True - I missed that, having seen that it's a Java question. It's still not thread-safe or following good design principles in C# though :) (There's already a good Java answer suggesting AtomicInteger.)
|