[英]Picking random unique items from an arraylist
Say I want to pick 5 random colors from an array list like this one: 假设我要从像这样的数组列表中选择5种随机颜色:
static final List<Color> colors = new ArrayList<Color>();
static {
colors.add(Color.RED);
colors.add(Color.BLUE);
colors.add(Color.GREEN);
}
It's pretty easy I can just do this... 我可以很容易地做到这一点...
static Random random = new Random();
public static Color getRandomColor() {
return colors.get(random.nextInt(colors.size());
}
But what if I want to pick unique colors which aren't the same? 但是,如果我想选择不同的独特颜色怎么办? So say I pick RED, how can I make sure to not pick RED again; 因此,说我选择红色,如何确保不再选择红色? preferably without removing it from the list, too. 最好也不要将其从列表中删除。
EDIT: 编辑:
I've found something that works: 我发现了一些可行的方法:
Color generatedColor = Theme.randomColor();
for (int i = 0; i < pie.segments.size(); i++) {
if (generatedColor == pie.segments.get(i).getColor()) {
generatedColor = Theme.randomColor();
return;
}
}
this.color = generatedColor;
However someone suggested I just remove them all and re-add once I've finished generating them all, which method should I go for? 但是有人建议我将它们全部删除,并在完成全部生成后重新添加,我应该选择哪种方法?
EDIT 2: 编辑2:
After shuffling, I get this: http://i.imgur.com/HPKQNFH.png 改组后,我得到以下信息: http : //i.imgur.com/HPKQNFH.png
Thanks! 谢谢! :) :)
Use remove
method, which return the object at the position and then remove it. 使用remove
方法,该方法将对象返回到该位置,然后将其删除。
Then your method becomes: 然后您的方法变为:
public static Color getRandomColor() {
return colors.remove(random.nextInt(colors.size());
}
and when the list size is 0, reinsert all the colors. 当列表大小为0时,重新插入所有颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.