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

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

java - ID generator for the Objects created

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...