如何更改特定范围的ArrayList?

Cod*_*Guy 12 java collections 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)
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 23

使用List.subListCollections.shuffle,像这样:

Collections.shuffle(list.subList(start, end));
Run Code Online (Sandbox Code Playgroud)

(注意第二个索引是subList 独占的,所以end+1如果你想end在shuffle中包含索引,请使用.)

由于List.subList返回列表视图,(通过shuffle方法)对子列表所做的更改也会影响原始列表.


Boh*_*ian 7

是 - 使用List.sublist(开始,结束)Collections.shuffle(),即:

Collections.shuffle(list.sublist(start, end));
Run Code Online (Sandbox Code Playgroud)

sublist返回列表的视图,因此当您对其进行随机播放时,您将对实际列表进行随机播放,但仅在开始和结束之间