1

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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
The_Liner
  • 63
  • 1
  • 7

1 Answers1

1

I use random ID's like this when moving data records from one system to another. I generally use a UUID (Universally Unique IDentifier) so I can clearly distinguish any one record from any of its (potentially millions of) counterparts.

Java has pretty good support for them. Try something like this:

import java.util.UUID;

private String generateUserID(String prefix, int digitNumber) {
  String uuid = UUID.randomUUID().toString();
  return prefix + digitNumber + uuid;  // Use the prefix and digitNumber however you want.
}

JavaDocs: https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html#randomUUID()

thehale
  • 913
  • 10
  • 18