ID generator for the Objects created

后端 未结 3 1856
情歌与酒
情歌与酒 2021-01-04 21:56

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

相关标签:
3条回答
  • 2021-01-04 22:32

    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).

    0 讨论(0)
  • 2021-01-04 22:46

    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();
    }
    
    0 讨论(0)
  • 2021-01-04 22:49

    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();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题