随机迭代ArrayList< Integer>.在Java中 [英] Randomly iterate over ArrayList<Integer> in Java

查看:46
本文介绍了随机迭代ArrayList< Integer>.在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&lt; Integer&gt;.在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆