且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中生成6个不同的随机数

更新时间:2023-02-06 08:59:00

在 Java 8 中:

In Java 8:

final int[] ints = new Random().ints(1, 50).distinct().limit(6).toArray();

在 Java 7 中:

In Java 7:

public static void main(final String[] args) throws Exception {
    final Random random = new Random();
    final Set<Integer> intSet = new HashSet<>();
    while (intSet.size() < 6) {
        intSet.add(random.nextInt(49) + 1);
    }
    final int[] ints = new int[intSet.size()];
    final Iterator<Integer> iter = intSet.iterator();
    for (int i = 0; iter.hasNext(); ++i) {
        ints[i] = iter.next();
    }
    System.out.println(Arrays.toString(ints));
}

只是有点乱.将 Set 拆箱到 int[] 中非常乏味,这一事实并没有帮助.

Just a little messier. Not helped by the fact that it's pretty tedious to unbox the Set<Integer> into an int[].

应该注意的是,这个解决方案应该可以很好地要求值的数量明显小于的范围.由于 1..496 大很多,所以你没问题.否则性能会迅速下降.

It should be noted that this solution should be fine of the number of required values is significantly smaller than the range. As 1..49 is quite a lot larger than 6 you're fine. Otherwise performance rapidly degrades.