java Java随机集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/969573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:37:58  来源:igfitidea点击:

Java random collection

java

提问by Sefler

Is there a kind of Java collection that the order of my fetching is random? For example, I put integer 1, 2, 3 into the collection and when I try to print them all the result can be "1 2 3","3 2 1" or "1 3 2"?

是否有一种 Java 集合,我的提取顺序是随机的?例如,我将整数 1、2、3 放入集合中,当我尝试打印它们时,所有结果可能是“1 2 3”、“3 2 1”或“1 3 2”?

回答by Silfverstrom

If you just want a random sequence you could use Collections.shuffle

如果你只想要一个随机序列,你可以使用 Collections.shuffle

    List<Integer> list = new LinkedList();
    //Add elements to list
    Collections.shuffle(list);

回答by Jon Skeet

Take a normal collection and shuffle it, then iterate over it in a normal way.

取一个正常的集合并对其进行洗牌,然后以正常方式对其进行迭代。

You can use java.util.Collections.shuffle(List<T>)to do the shuffling.

你可以java.util.Collections.shuffle(List<T>)用来做洗牌。

回答by Bill the Lizard

Just shufflethe collection.

只是洗牌集合。

If the collection muststay in order you could access elements at random indices, but then you have to keep track of ones you've used before (maybe, it depends on your application), and this can be very inefficient. A better solution, if memory is no obstacle, would be to just make a copy and shuffle that.

如果集合必须保持有序,您可以访问随机索引处的元素,但是您必须跟踪您以前使用过的元素(也许,这取决于您的应用程序),这可能非常低效。如果内存没有障碍,更好的解决方案是制作一个副本并随机播放。

回答by Tom Jefferys

Not that I'm aware of. You could always put the values in a list, and use Collections.shuffle to put the values into a random order.

不是我所知道的。您始终可以将值放在列表中,并使用 Collections.shuffle 将值放入随机顺序中。