Java生成非重复随机数
我想在 Java 中创建一组不重复的随机数.
I want to create a set of random numbers without duplicates in Java.
例如,我有一个数组来存储从 0 到 9999 的 10,000 个随机整数.
For example I have an array to store 10,000 random integers from 0 to 9999.
这是我目前所拥有的:
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?
推荐答案
Integer[] arr = {...};
Collections.shuffle(Arrays.asList(arr));
例如:
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));
}
相关文章