Fernando Martinez Fernando Martinez - 2 years ago 105
Java Question

Java generating non-repeating random numbers

I want to create a set of random numbers without duplicates in Java.

For example I have an array to store 10,000 random integers from 0 to 9999.

Here is what I have so far:

import java.util.Random;
public class Sort{

public static void main(String[] args){

int[] nums = new int[10000];

Random randomGenerator = new Random();

for (int i = 0; i < nums.length; ++i){
nums[i] = randomGenerator.nextInt(10000);

But the above code creates duplicates. How can I make sure the random numbers do not repeat?

Answer Source
Integer[] arr = {...};

For example:

public static void main(String[] args) {
    Integer[] arr = new Integer[1000];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download