如何随机播放 ArrayList 的特定范围? [英] How can I shuffle a specific range of an ArrayList?

查看:24
本文介绍了如何随机播放 ArrayList 的特定范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我知道要打乱 ArrayList,方法 Collections.shuffle() 存在,但是这会打乱整个列表.

我该如何编写方法(或者,有人可以编写并展示给我看吗?),例如:

私有ArrayList列表;/*** 打乱 [start, end] 范围内数组列表的浓度,和* 对列表中的其他索引没有任何影响.*/public void shuffleArrayListInTheRange(int start, int end)

解决方案

使用 List.subListCollections.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屋!

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