Java Collection How to - Generate unique random numbers in an array








Question

We would like to know how to generate unique random numbers in an array.

Answer

import java.util.Arrays;
import java.util.Random;
//from w  ww . jav a  2  s . com
public class Main {

  public static void main(String args[]) {
    int rnd;
    Random rand = new Random();
    int[] nums = new int[50];
    
    boolean[] check = new boolean[50];
    
    for (int k = 0; k < 50; k++) {
      rnd = rand.nextInt(50);
      //check if the check array index has been set
      //if set regenerate since it is duplicate 
      while (check[rnd]) {
        rnd = rand.nextInt(50);
      }
      nums[k] = rnd;
      check[rnd] = true;
    }
    System.out.println(Arrays.toString(nums));

  }
}

The code above generates the following result.