How to Generate Unique Positive Long Number in Java?
Java provides different ways to generate random numbers, using some built-in methods and classes, but most of them do generate unique positive long numbers like java.util.Random class, Math.random method and ThreadLocalRandom class, and many others. But in most of these either with randomness uniqueness is not followed along which means a random number generated by those methods is not unique, this can be verified by providing a small range to Random().
Few other libraries which are actually capable to produce unique number come with the drawback that the output number include both positive and negative number, here uniqueness might be followed but if the requirement is aligned towards producing a positive unique number, these libraries will not be useful
To produce a positive unique(extremely low chances of repetition) long value in java the well-known UUID library which is also widely used for generating unique strings, using UUID unique long number of the desired length can be obtained as below
UUID.randomUUID().toString() produces a unique String of length 36 and is made up of characters (alphabets and “-“) and digits.
where uniqueNoSize represents the size of the unique number required, it should be less than equal to 38 as generateUUIDNo length is 38.
Please Login to comment...