随机迭代ArrayList< Integer>.在Java中 [英] Randomly iterate over ArrayList<Integer> in Java
问题描述
似乎是一个非常基本的问题.我有一个 ArrayList< Integer>al
,我想对其进行迭代.通常,
Seems a very basic question. I've an ArrayList<Integer> al
and I would like to iterate over it. Normally,
for(int i : al) {
// some code
}
可以解决问题.但是我的要求是不按顺序进行迭代,而是随机进行.
does the trick. But my requirement is to iterate not in sequence but randomly.
推荐答案
You can use Collections.shuffle()
on the list.
请注意,这会随机排列列表,因此,如果顺序很重要,则应制作一个副本(并随机排列副本).
Note that this will shuffle the list itself, so if order is important you should make a copy of it (and shuffle the copy).
List<Customer> newList = new ArrayList<>( oldList ) ;
Collections.shuffle( newList ) ;
或者,您可以创建一个包含元素 0-List.size()-1
的随机数组,并使用这些元素作为索引来访问 List
中的随机"元素
Alternatively you could create a random array which has elements 0 - List.size()-1
and using those as indices to access "random" elements in the List
.
这篇关于随机迭代ArrayList< Integer>.在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!