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