Elegant way to assign object id in Java

后端 未结 4 1607
感情败类
感情败类 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();
       }
    }
    
    0 讨论(0)
  • 2020-12-09 04:38

    There is another way to get unique ID's. Instead of using an int or other data type, just make a class:

    final class ID
    {
      @Override
      public boolean equals(Object o)
      {
         return this==o;
      }
    }
    
    public Apple
    {
      final private ID id=new ID();
    }
    

    Thread safe without synchronizing!

    0 讨论(0)
  • 2020-12-09 04:43

    Use java.util.UUID.randomUUID()

    It is not int, but it is guaranteed to be unique:

    A class that represents an immutable universally unique identifier (UUID).


    If your objects are somehow managed (for example by some persistence mechanism), it is often the case that the manager generates the IDs - taking the next id from the database, for example.

    Related: Jeff Atwood's article on GUIDs (UUIDs). It is database-related, though, but it's not clear from your question whether you want your objects to be persisted or not.

    0 讨论(0)
  • 2020-12-09 04:51

    Have you thought about using UUID class. You can call the randomUUID() function to create a new id everytime.

    0 讨论(0)
提交回复
热议问题