1

I have the following method to create random ids that look like positive long numbers (I can't use UUID.randomUUID().toString() for non-technical reasons that are outside the scope of this question):

public String createRandomId() {
    UUID uuid = UUID.randomUUID();
    return String.valueOf(uuid.getMostSignificantBits() & Long.MAX_VALUE) +
            (uuid.getLeastSignificantBits() & Long.MAX_VALUE);
}

The question is simple: would this method yield a unique result? (I mean, unique like in UUID.randomUUID())

fps
  • 33,623
  • 8
  • 55
  • 110
  • 1
    Java supports unsigned tostring for integers. `Long.toUnsignedString(long)` – vandench May 27 '19 at 15:54
  • 2
    You would also need to add a separator to ensure that it is unique. – vandench May 27 '19 at 15:58
  • 1
    Probably because you just sacrifice 2 bits from 128 to have positive long`s. You can compute the probability of collision using the wiki formula from [Universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier). Have you considered this post [How to generate unique positive Long using UUID](https://stackoverflow.com/questions/15184820/how-to-generate-unique-positive-long-using-uuid)? – Butiri Dan May 27 '19 at 16:25
  • @vandench Thanks for pointing me to `Long.toUnsignedString(long)`, and about the separator... actually that was the heart of my question... Do you think that left-padding the least significant bits with `0`s would account as a valid separator? – fps May 27 '19 at 16:36
  • @ButiriDan Yes, thank you. I took the idea from that very question. – fps May 27 '19 at 16:36
  • 1
    Padding would work, you just want to make sure `123+21` != `12+321`. You could use a delimiter, use 16 hex characters for each long, find the largest long value and count the digits and pad, really anything works as long as you can determine which number is which. You could hypothetically even represent it in Base64 as a 128 bit integer. – vandench May 27 '19 at 18:17

0 Answers0