2011-08-16 58 views
11

在Java中,我知道要洗牌ArrayList,方法Collections.shuffle()存在,但是這將洗牌整個列表。如何混洗ArrayList的特定範圍?

我如何寫一個方法(或者,有人可以寫出來,讓我看看嗎?),如以下幾點:

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) 
+1

而令人驚訝地看到四個答案几乎說了同樣的事情。 :) – Malcolm

回答

22

使用List.subListCollections.shuffle,像這樣:

Collections.shuffle(list.subList(start, end)); 

(注意第二個索引subList獨家,所以使用end+1如果你想包括end索引在shuffle中。)

由於List.subList返回製成的視圖列表的,改變(由混洗方法)到子列表中,也將影響原始列表。

2
Collections.shuffle(list.subList(start, end+1)); 

注意+1,因爲subList()的結束索引是排他性的。

0

很簡單

public void shuffleArrayListInTheRange(int start, int end) { 
    Collections.shuffle(list.subList(start, end)); 
} 
+0

呃,我遲到了! :( – adarshr