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().
Example 1:
Java
import java.io.*;
import java.util.Random;
class GFG {
public static void main(String[] args)
{
Random random = new Random();
int rand = 0 ;
while ( true ) {
rand = random.nextInt( 5 );
if (rand != 0 )
break ;
}
System.out.println(rand);
}
}
|
Example 2:
Java
import java.io.*;
import java.util.Random;
class GFG {
public static void main(String[] args)
{
Random random = new Random();
double d = random.nextDouble();
System.out.println(d);
double d1 = Math.random();
System.out.println(d1);
}
}
|
Output
0.48783050588815524
0.05301287078228778
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.
Example:
Java
import java.math.BigInteger;
import java.util.UUID;
class GFG {
public static void main(String[] args)
{
String generateUUIDNo = String.format( "%010d" , new BigInteger(UUID.randomUUID().toString().replace( "-" , "" ), 16 ));
String unique_no = generateUUIDNo.substring( generateUUIDNo.length() - 10 );
System.out.println(unique_no);
}
}
|
where uniqueNoSize represents the size of the unique number required, it should be less than equal to 38 as generateUUIDNo length is 38.
Last Updated :
05 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...