-1

I want to generate a serial number for one of my classes like xxxxxxxxxx and I want its length to be exactly 10 characters.

how can I generate random UUID by only using "1234567890". is there something I have to pass to constructor or UUID.randomUUID()?

and how can I give it a fixed length?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

4

UUID gives 128 bits, where the range of 10 digits is about 33 bits, using 210 is approx. 103. So the uniqueness is reduced.

One can do something like:

String randomCode() {
    UUID uuid = UUID.randomUUID();
    long lo = uuid.getLeastSignificantBits();
    long hi = uuid.getMostSignificantBits();
    lo = (lo >> (64 - 31)) ^ lo;
    hi = (hi >> (64 - 31)) ^ hi;
    String s = String.format("%010d", Math.abs(hi) + Math.abs(lo));
    return s.substring(s.length() - 10);
}

This folds the 128 bits almost 4 fold to deliver 10 digits. That is as said not necessarily unique.

It might be better to use a secret pseudo-random sequence, requiring saving a state. Or any of the other random generators / System.nanos().

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138