在 java 中创建一个包含 10 个唯一数字的数组

make an array with 10 unique numbers in java

第一次在这里提问

我想用从 0 到 9 的 10 个唯一的 int 数字制作 ArrayList。 我执行后续步骤:

  1. 创建空数组列表
  2. 添加第一个随机数,以便稍后检查是否重复
  3. 接下来我创建新的随机 int 值,检查我是否已经在 ArrayList 中有这个值。如果我有 - 我尝试另一个号码,如果我没有 - 我添加这个号码。
  4. 如果我得到 10 个数字,我就停止循环

我的代码:

public static void main(String[] args) {

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

    int q = rd.nextInt(10);
    list.add(q);

    while (true) {
        int a = rd.nextInt(10);
        for (int b=0;b<list.size();b++){
            if (a == list.get(b)) break;
            else list.add(a);
        }
        if (list.size() == 10) break;
    }
    System.out.println(list);
}

但我在控制台中看到的只是无尽的过程。

问题是 - 是否有另一种方法可以使 ArrayList 具有 10 个唯一数字(0 到 9)?

用数字初始化 ArrayList 后使用 Collections.shuffle

ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
{
    list.add(i);
}
Collections.shuffle(list);

这将在线性时间内 运行 因为 ArrayListRandomAccess

使用 Java 8 个流

List<Integer> shuffled = 
   // give me all the numbers from 0 to N
   IntStream.range(0, N).boxed()
        // arrange then by a random key
        .groupBy(i -> Math.random(), toList())
        // turns all the values into a single list
        .values().flatMap(List::stream).collect(toList());