![](/img/trans.png)
[英]Out of bounds exception printing in for loop less than arraylist size in java
[英]Size of the loop is printing less numbers than i want to be in my Set JAVA
基本上我想生成 1-10 之間的隨機數,這些隨機數被放入我的集合中。 問題是我的循環大小是從 0 到 9,它會生成隨機數,但是一旦是 5 個數字,一次是 7 個數字,一次是 3 個數字,而不是 9 個數字。 為什么?
private static Set<Integer> losowanie() {
Set<Integer> result = new TreeSet<>();
Random random = new Random();
for (int i = 0; i < 10; i++){
result.add(random.nextInt(10) + 1);
}
return result;
}
}
我也在用while循環做同樣的事情,它也做同樣的事情。
因為 Set collections 不能有重復的屬性,也就是說,當你生成數字時,如果隨機數中生成相同的數字,你的 Set 只能持有唯一的數字。
public static void main(String[] args) {
Set<Integer> result=new TreeSet<>();
for (int i = 0; i < 10; i++) {
result.add(1);
}
//only one data: [1]
System.out.println(result);
result=new TreeSet<>();
for (int i = 0; i <10 ; i++) {
result.add(i);
}
//ten data:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println(result);
}
首先,您的循環索引從 0 到 9,即十次迭代。
因此,您可能期望您的集合中有十個數字。 但是集合元素必須是唯一的,並且您插入的元素是從一組僅有的十種可能性中隨機選擇的。
發生這種情況的幾率是10! ÷ 10 10或約 0.036%。 繼續運行你的程序。
如果您的目標是隨機排列十個不同的數字,請改為執行以下操作:
List<Integer> result = IntStream.rangeClosed(1, 10)
.boxed()
.collect(Collectors.toList());
Collections.shuffle(random);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.