I want to generate ID number for an object in the following rules: Each new object will get a unique ID number (the first one will be 1), and then each new object will get the lowest available ID number.
For instance if I declare 4 object Object 1 ID: 1 Object 2 ID: 2 Object 3 ID: 3 Object 4 ID: 4
then if I delete object number 3. so the next object that will be made will get ID: 3 and not 5.
what is the best way of doing that ID generator?
Best How To :
I assume you want to do it in Java. I suggest the following:
Have a sequence that is used to provide entities with IDs. It is quite simple and I think require no detailed explanation - it just returns 1, 2, 3, etc.
Now we need to handle deletion. Together with the sequence I'd suggest to have a
SortedSet of IDs that was deleted and can be assigned to new entities.
Having this two structures together, act like:
If set is not empty, return its first value and remove it from a set. It will be the lowest value, because you use
If it is empty, just return next number from the sequence.
Of course, you'll need to handle atomicity of this operation and may encounter concurrency issues, but detailed discussion of it is a little bit offtopic for this question IMO.