ID generator for the Objects created

后端 未结 3 1864
情歌与酒
情歌与酒 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: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();
        }
    
    }
    

提交回复
热议问题