Generating Unique Random Number Upto A Limit In Java

Java Spring Decoded
Javarevisited
Published in
1 min readJul 3, 2023

Here we will try to figure out a way to generate unique random number within a upper limit .

The problem with general random number generation is there is a chance of collision but we want to return unique random numbers each time a client call us , this is one of the solution which is easy to understand .

import java.util.*;

public class GenerateRandom {
public static int MAX = 100;

Set<Integer> numberSet = new HashSet<>();




public Integer generateRandomNumber(){
Random random = new Random();
if(numberSet.size() == 100){
return -1;
}
else{
int temp = random.nextInt(MAX) ;
while(numberSet.contains(temp)){
temp = random.nextInt(MAX);
}
numberSet.add(temp);
return temp;
}
}
}

here , we are maintaining a hash set of the numbers we have generated and checking each time for the generated number if it is present in the set or not , and we keep on doing it till we get the unique number .

here , we have implemented with a upper limit of 100 .

P.S :- There is a drawback to this method as there will be less numbers left , there will be more collisions , hence high response time .

I will update with a better algorithm to do so.

--

--

Java Spring Decoded
Javarevisited

All Articles related to java , spring , Backend Development and System Design.