Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to assign object id in Java

Tags:

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

like image 268
user318247 Avatar asked Oct 24 '10 17:10

user318247


People also ask

How do you assign an object in Java?

First, define a class with any name 'SampleClass' and define a constructor method. The constructor will always have the same name as the class name and it does not have a return type. Constructors are used to instantiating variables of the class. Now, using the constructors we can assign values.

What is object ID in Java?

ObjectId(int timestamp, int machineIdentifier, short processIdentifier, int counter) Creates an ObjectId using the given time, machine identifier, process identifier, and counter. ObjectId(java.lang.String hexString) Constructs a new instance from a 24-byte hexadecimal string representation.

What is reference ID in Java?

Reference ID is generated by new operator in the stack and it is a memory location which contains the memory location of an object in hashcode form. Reference ID is the only way to reach the object.


3 Answers

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();
   }
}
like image 58
Codemwnci Avatar answered Oct 17 '22 17:10

Codemwnci


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.

like image 36
Bozho Avatar answered Oct 17 '22 18:10

Bozho


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

like image 5
Amir Raminfar Avatar answered Oct 17 '22 19:10

Amir Raminfar