java - 在 Java 中有效地生成唯一的随机数

标签 java random

我想生成 0 到 999,999 范围内的唯一随机数。

为了实现这一目标,我尝试了:

ArrayList<Integer> list = new ArrayList<Integer>();

        for (int i = 0; i < 999999; i++) { 
            list.add(new Integer(i)); // Add numbers from 0 - 999,999 into ArrayList
        }

        Collections.shuffle(list); // shuffle them

        for (int i = 0; i < 10; i++) {
            System.out.println(list.get(i)); // printed unique numbers
        }

问题是我要生成的数字越大,耗时越长,对于上面的方法,大概耗时700ms

但如果我使用 Random() 生成它们而不过滤重复数字,它只需要 2ms

for(int i = 0; i<10; i++) {
  int digit = 0 + new Random().nextInt((999999 - 0) + 1); 
  System.out.println(digit);
}

有没有其他方法可以更有效地生成唯一的随机数?

最佳答案

如果您只需要 10 个,则无需创建 1000000 个数字的列表并将它们全部打乱。也无需编写 new Integer(i)(您可以只使用 ).

在 Java 8 中,有一种非常简单的方法可以做到这一点:

int[] arr = ThreadLocalRandom.current().ints(0, 1000000).distinct().limit(10).toArray();
System.out.println(Arrays.toString(arr));

如果您使用的是 Java 7 或更低版本,您可以这样做:

Random rand = new Random(); // Only do this in Java 6 or below. Now you should use ThreadLocalRandom.current().
int[] arr = new int[10];
Set<Integer> set = new HashSet<Integer>();
for (int index = 0, a; index < 10;)
    if (set.add(a = rand.nextInt(1000000)))
        arr[index++] = a;
System.out.println(Arrays.toString(arr));

关于java - 在 Java 中有效地生成唯一的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33908199/

相关文章:

java - JTA 事务 : What happens if an exception happens but rollback is not called on the transaction?

python - 如何在循环中不断更新张量的值

python - 元组的 Numpy 随机选择

python - 为什么我的代码结果 'module' 对象不可下标?

java - 不可变类中的编译时错误 : (final) variable might not have been initialized

java - 为什么PatriciaTrie中无法访问 `floorEntry`等方法?

java - 写入图像后无法将响应 header 设置为 http 状态 302 的位置

ios - random() 会改变吗?

c# - 如何生成具有最大值的随机 uint?

java - 线程 "main"com.google.apphosting.api.ApiProxy$CallNotFoundException : The API package 'mail' or call 'Send()' was not found 中的异常