I need a class which creates Objects assigning an ID to each Object created. This ID is as usual an int attribute to the class. I want this value (ID) to be increased each time an Object is created and then to be assigned to that Object starting with 1. It strikes me that I need a static int attribute.
How can I initialize this static attribute?
Should I create a separate method to do the increment of the ID (as an ID generator) which is invoked inside the constructor?
What is in general the most effective and well-designed manner to implement that?
You could also try java.util.concurrent.AtomicInteger, which generates IDs in
You may use this in a static context like:
private static final AtomicInteger sequence = new AtomicInteger();
private SequenceGenerator() {}
public static int next() {
return sequence.incrementAndGet();
}
Just like you mention use a static int
for the id, and increment it when creating new objects.
class MyObject {
private static int counter = 0;
public final int objectId;
MyObject() {
this.objectId = counter++;
}
}
Please note that you need to protect counter++
if MyObject
is created by multiple threads (for example using AtomicInteger
as the other answers suggest).
I would suggest to use AtomicInteger
, which is thread-safe
class MyObject
{
private static AtomicInteger uniqueId=new AtomicInteger();
private int id;
MyObject()
{
id=uniqueId.getAndIncrement();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With