Spedwards
Spedwards

Reputation: 4492

Generate Unique Object ID

I'm trying to generate a new unique identifier for each object in a class, without using a static nextID field to just increment. Using that will create complications when unloading and unloading the program.

I came up with a solution to loop through the objects in a static method checking them all but for some unknown reason to me, it won't exit the while-loop.

I have been testing it in ideone.com here trying to create 5 objects to begin with, though it won't even create one.

Without having to go to the link to view the whole testing code, below is the method I'm using.

public static int newRandomID() {
    int randomID = 0;
    boolean notUnique = true;

    while (notUnique) {
        randomID = (int) (Math.random() * 999999 + 1);
        for (Example e : examples) {
            if (e.ID == randomID) {
                notUnique = true;
                break;
            }
            notUnique = false;
        }
    }
    return randomID;
}

Have I just made a stupid mistake that I'm too blind to see, or is there a reason that this isn't working?

Upvotes: 2

Views: 1070

Answers (3)

aviad
aviad

Reputation: 1573

Tried to execute your code (from the link you sent): After you created and printed 50 new ids, I tried to generate 150,000 more:

for (int i = 0; i < 150000; i++)
        new Example();

and... it works perfectly fine! Just took it a minute or so (which makes sense). If I try to create only 15,000 records it works in less than a second.

Which leads me to the conclusion that miss rate is exponentially high and starts to be unbearable once you reach 15% of the ids capacity.

Don't continue with this solution. Use a different approach such as a stored sequential number (if you store the records). If you don't store the records, I don't see a reason why not to use a static int variable.

Upvotes: 0

Priyamal
Priyamal

Reputation: 2969

your notUnique is bit confusing and i think you are doing it wrong in here

if (e.ID == randomID) {
            notUnique = true;
            break;
}

you dont need to break the statement if the id exists. i changed you code may be this helps.

    int randomID = 0;
    boolean ContinueLoop = true;

    while (ContinueLoop) {
        randomID = (int) (Math.random() * 999999 + 1);
        boolean exist = false;
        for (Example e : examples) {
            if (e.ID == randomID) {
                exist = true;
            }else{
                exist = false;
                break;  
            }

        }

        if(exist==false){
            ContinueLoop = false;
        }else{
            ContinueLoop = true;
        }

    }
    return randomID;

Upvotes: 0

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

If all you need is a unique identifier (that need not be sequential) and it dosn't have to be an integer, have a look at java.util.UUID

Upvotes: 5

Related Questions