Elegant way to assign object id in Java

后端 未结 4 1620
感情败类
感情败类 2020-12-09 03:52

I have a class for objects ... lat\'s say apples.

Each apple object mush have a unique identifier (id)... how do I ensure (elegantly and efficiently) that newly crea

4条回答
  •  余生分开走
    2020-12-09 04:35

    have a static int nextId in your Apple class and increment it in your constructor.

    It would probably be prudent to ensure that your incrementing code is atomic, so you can do something like this (using AtomicInteger). This will guarantee that if two objects are created at exactly the same time, they do not share the same Id.

    public class Apple {
        static AtomicInteger nextId = new AtomicInteger();
        private int id;
    
        public Apple() {
            id = nextId.incrementAndGet();
       }
    }
    

提交回复
热议问题