0

Using UUID.randomUUID() is best when we need the universal unique number of 36 char as alfa numeric but can't see an authentic function to generate the 36 digits number (Unique).

String lUUID = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));

The above code we can use to generate the unique number but it's giving 40 digits and no guarantee of being uniqueness.

  • 3
    What is the guarantee of uniqueness for the UUID? Why isn't your big integer just as unique as the original UUID? Considering all you're doing is converting it from a String representation and making it an Integer representation? What is **your** criteria for uniqueness? – matt Sep 08 '22 at 21:26
  • 1
    Every number is unique. – shmosel Sep 08 '22 at 21:27
  • 1
    UUID collisions are [extraordinarily rare](https://stackoverflow.com/a/24876263/6296561). You can never truly guarantee uniqueness when you randomize anything. Reducing the number of options, however, increases the probability of a collision. If you truly need no collisions and a truly 0% (and not effectively 0%) chance of a collision, you need a way to centrally manage the number used. Otherwise, collisions can happen on paper. However, for the vast majority of applications, effectively 0% is good enough – Zoe Sep 08 '22 at 21:35
  • Playing Russian roulette with a revolver with 1,000,000,000,000,000,000,000,000,000,000,000,000 chambers – g00se Sep 08 '22 at 21:58

1 Answers1

2

You definitely can't guarantee uniqueness any more than UUID.randomUUID() can. Without synchronizing with, like, a server somewhere, you can't guarantee that; you can just make it improbable.

But to make it improbable as possible, just use the random constructor:

SecureRandom random = new SecureRandom()
BigInteger bigint;
do {
  bigint = new BigInteger(120, random); // 2^120 > 10^36
} while (bigint.compareTo(BigInteger.TEN.pow(36)) >= 0);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413