简体   繁体   中英

Elegant way to assign object id in Java

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 created has unique id.

Thanks

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

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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM