Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
251 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could also try java.util.concurrent.AtomicInteger, which generates IDs in

  1. a atomic way and
  2. sequential

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...