【发布时间】:2021-09-15 15:31:10
【问题描述】:
我正在尝试编写一个方法来获取从 1 到 10 的数字列表,其中不会有重复项。此外,成员不得为零。 但是,经过多次尝试我未能解决问题,这是我的代码:
public ArrayList<Integer> dobijNiz() {
int min = 1;
int max = 10;
ArrayList<Integer> lista = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 11; i++) {
int broj = random.nextInt((max - min) + 1) + min;
lista.add(broj);
}
System.out.println(lista);
return lista;
}
输出:
[2, 3, 3, 3, 4, 6, 10, 8, 2, 7, 9]
我忘了说 Collections.shuffle 不起作用
【问题讨论】:
-
编程到
List接口(而不是在任何地方指定ArrayList)。List<Integer> lista = IntStream.range(min, max).boxed().collect(Collectors.toList());然后Collections.shuffle(lista, ThreadLocalRandom.current()); -
问题有问题。如果您需要 10 个随机数并且列表大小为 10,那么它总是必须是 1 到 10 之间的数字。假设您期望 5 随机从 1 到 10,那么这就是它的样子。您还应该检查 max-min 是否大于 count 以确保它确实进入无限循环 :) [![Working Example][1]][1] [1]: i.stack.imgur.com/BOLmw.gif
标签: java arrays list sorting arraylist