问题描述
我为整数创建了一个 ArrayList,我想用 200 个数字填充它.每个数字可以在 0 到 1023 之间的范围内.
I've created an ArrayList for integers which I would like to fill with 200 numbers. Each number can be within a range between 0 and 1023.
因此我写了这段代码:
Random rand = new Random();
ArrayList<Integer> values = new ArrayList<Integer>();
int START_AMOUNT = 200;
for(int i = 0; i < START_AMOUNT;
values.add(rand.nextInt(1024));
}
如您所见,for 循环会将 200 个随机数添加到值"ArrayList,从 0 到 1023.现在我的问题是我希望数组只有唯一的数字.如何告诉 Random 类不要生成任何已存在于 ArrayList 中的数字?
As You might see, the for-loop will add 200 random numbers to the "values" ArrayList, from 0 to 1023. Now my problem is that I want the Array to have only unique numbers. How can I tell the Random class not to generate any numbers that already are existent in the ArrayList?
推荐答案
我要做的是创建一个由 1,2,3,...,1023 组成的 1023 int 数组.然后你洗牌,你只取前 200 项:
What I'd do is creating an array of 1023 int composed by 1,2,3,...,1023. Then you shuffle it, and you take only the 200 first terms :
List<Integer> ints = new ArrayList<Integer>();
for(int i = 1; i <= 1023; i++)
{
ints.add(i);
}
Collections.shuffle(ints);
按照@Bohemian♦ 的建议进行编辑
List<Integer> result = ints.subList(0,200);
这篇关于将唯一的随机数添加到整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!