user318247
user318247

Reputation: 665

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

Upvotes: 19

Views: 22274

Answers (4)

Codemwnci
Codemwnci

Reputation: 54924

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

Upvotes: 26

Ishtar
Ishtar

Reputation: 11662

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!

Upvotes: 2

Bozho
Bozho

Reputation: 597234

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.

Upvotes: 13

Amir Raminfar
Amir Raminfar

Reputation: 34169

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

Upvotes: 5

Related Questions