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.
Yes - use List.sublist(start, end) and Collections.shuffle() that, ie:
Collections.shuffle(list.sublist(start, end));
sublist
returns a view of the list, so when you shuffle it, you shuffle the actual list but only between start and end
Collections.shuffle(list.subList(start, end+1));
Note the +1, because the end index of subList()
is exclusive.
It's simple
public void shuffleArrayListInTheRange(int start, int end) {
Collections.shuffle(list.subList(start, end));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.