如何打乱 ArrayList 的特定范围?
在Java中,我知道要打乱ArrayList,存在Collections.shuffle()方法,但是这会打乱整个列表。
我如何编写一个方法(或者,有人可以编写它并向我展示吗?),如下所示:
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
列表。 subList
和Collections.shuffle
,如下所示:(注意,第二个索引为
subList
exclusive,因此使用end+1
如果您想在随机播放中包含end
索引。)由于
List.subList
返回一个视图列表中,对子项进行的更改(通过 shuffle 方法)列表,也会影响原来的列表。Use
List.subList
andCollections.shuffle
, like this:(Note that the second index to
subList
exclusive, so useend+1
if you want to includeend
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.是 - 使用 列表.sublist(start, end) 和 Collections.shuffle() 即:
sublist
返回列表的视图,因此当您对其进行洗牌时,您会洗牌实际列表,但仅在开始和结束之间进行洗牌Yes - use List.sublist(start, end) and Collections.shuffle() that, ie:
sublist
returns a view of the list, so when you shuffle it, you shuffle the actual list but only between start and end请注意 +1,因为
subList()
的结束索引是排他的。Note the +1, because the end index of
subList()
is exclusive.很简单
It's simple