Randomly iterate over ArrayList in Java

后端 未结 5 1383
滥情空心
滥情空心 2020-12-30 14:36

Seems a very basic question. I\'ve an ArrayList al and I would like to iterate over it. Normally,

for(int i : al) {
    // some c         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 14:59

    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 newList = new ArrayList<>( oldList ) ;
    Collections.shuffle( newList ) ;
    

    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.

提交回复
热议问题