mardi 30 mars 2021

How to ensure values produces randomly are unique in Java

When generating a random value, I need to ensure that the generateUserID() method generates a "random and unique" value every time.

private String generateUserID(String prefix, int digitNumber) 
{
    return prefix + String.valueOf(digitNumber < 1 ? 0 : new Random()
            .nextInt((9 * (int) Math.pow(10, digitNumber - 1)) - 1)
            + (int) Math.pow(10, digitNumber - 1));
}    

No output from this method should be the same as another value. Thus, I need to refactor the code, but I cannot use any loop.




Aucun commentaire:

Enregistrer un commentaire