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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With