Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random ID numbers that can't be reused in java?

Tags:

java

For my current java project, I am trying to generate random ID's for registered users. So far I have been using min +(int) (Math.random()*((max-min)+1)) as my formula to generate the random number. The problem that I am facing is that sometimes the numbers repeat themselves and my application wouldn't work with them.

    int min = 1001;
    int max = 1050;
    
    for (int i=1; i<=1; i++)
    {
    int a = min +(int) (Math.random()*((max-min)+1));
    
    

     }
     
     
  

I have tried using and incorporating

    Integer[] arr = new Integer[100];
    for (int i = 1; i < arr.length; i++) {
    arr[i] = i;
    }
    Collections.shuffle(Arrays.asList(arr));

but numbers generated would constantly come out as "null" and it would repeat the loop a few hundred times and flood my txt file.

like image 329
James Yonder Avatar asked Dec 30 '25 13:12

James Yonder


1 Answers

In general, random generators Random or Math.random() are not the correct ways to generate a unique id. As you mentioned, it could be repeated (and it will definitely be).

I would recommend two ways of generating ID.

The first one is to use AtomicInteger. This is good when your ID should be unique but not random.

private static final AtomicInteger ID = new AtomicInteger(0);

public static String generateUniqueId() {
    return String.valueOf(ID.incrementAndGet());
}

The second one, which is preferable to me, is to use UUID. This is good when your ID should be as unique as random.

public static String generateUniqueId() {
    return String.valueOf(UUID.randomUUID());
}

Another one, I can mention is to use System.nanoTime().

public static String generateUniqueId() {
    return String.valueOf(System.nanoTime());
}

Long ago I had some investigation and find out that this is pretty stable for normal payload. But in general, it could retrieve the same value if you build such a system, that should generate ID so often.

like image 144
oleg.cherednik Avatar answered Jan 01 '26 03:01

oleg.cherednik