Java: Unique 10 digit ID

后端 未结 4 1747
渐次进展
渐次进展 2020-12-13 15:57

I need to generate a unique 10 digit ID in Java. These are the restrictions for this ID:

  • Only Numeric
  • Maximum 10 digits
  • Possible to create up
4条回答
  •  抹茶落季
    2020-12-13 16:19

    This may be a crazy idea but its an idea :).

    • First generate UUID and get a string representation of it with java.util.UUID.randomUUID().toString()
    • Second convert generated string to byte array (byte[])

    • Then convert it to long buffer: java.nio.ByteBuffer.wrap( byte digest[] ).asLongBuffer().get()

    • Truncate to 10 digits

    Not sure about uniqueness of that approach tho, I know that you can rely on uniqueness of UUIDs but haven't checked how unique are they converted and truncated to 10 digits long number.

    Example was taken from JavaRanch, maybe there is more.

    Edit: As you are limited to 10 digits maybe simple random generator would be enough for you, have a look into that quesion/answers on SO: Java: random long number in 0 <= x < n range

提交回复
热议问题