如何随机播放 ArrayList 的特定范围? [英] How can I shuffle a specific range of an ArrayList?
问题描述
在 Java 中,我知道要打乱 ArrayList,方法 Collections.shuffle() 存在,但是这会打乱整个列表.
我该如何编写方法(或者,有人可以编写并展示给我看吗?),例如:
私有ArrayList列表;/*** 打乱 [start, end] 范围内数组列表的浓度,和* 对列表中的其他索引没有任何影响.*/public void shuffleArrayListInTheRange(int start, int end)
使用 List.subList
和 Collections.shuffle
,像这样:
Collections.shuffle(list.subList(start, end));
(注意subList
的第二个索引exclusive,所以如果你想包含end,请使用
end+1
代码> shuffle 中的索引.)
由于 List.subList
返回列表的视图,对子列表所做的更改(通过 shuffle 方法)也会影响原始列表.>
In Java, I know that to shuffle an ArrayList, the method Collections.shuffle() exists, however this shuffles the entire list.
How can I write a method (or, can someone write it and show me it?) such as the following:
private ArrayList<AnObject> list;
/**
* Shuffles the concents of the array list in the range [start, end], and
* does not do anything to the other indicies of the list.
*/
public void shuffleArrayListInTheRange(int start, int end)
Use List.subList
and Collections.shuffle
, like this:
Collections.shuffle(list.subList(start, end));
(Note that the second index to subList
exclusive, so use end+1
if you want to include end
index in the shuffle.)
Since List.subList
returns a view of the list, changes made (by the shuffle method) to the sub list, will also affect the original list.
这篇关于如何随机播放 ArrayList 的特定范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!