[英]How can I shuffle a specific range of an 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)
使用List.subList
和Collections.shuffle
,像这样:
Collections.shuffle(list.subList(start, end));
(注意subList
排他的第二个索引,所以如果你想在 shuffle 中包含end
索引,请使用end+1
。)
由于List.subList
返回列表的视图,因此(通过 shuffle 方法)对子列表所做的更改也会影响原始列表。
是 - 使用List.sublist(start, end)和Collections.shuffle() ,即:
Collections.shuffle(list.sublist(start, end));
sublist
返回列表的视图,所以当你打乱它时,你打乱了实际的列表,但只在开始和结束之间
Collections.shuffle(list.subList(start, end+1));
注意 +1,因为subList()
的结束索引是独占的。
这很简单
public void shuffleArrayListInTheRange(int start, int end) {
Collections.shuffle(list.subList(start, end));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.