Java generating non-repeating random numbers
duplicates, java, random
Solution
Integer[] arr = {...};
Collections.shuffle(Arrays.asList(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;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));
}
Problem
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?