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)
In order to shuffle elements of ArrayList with Java Collections, we use the Collections. shuffle() method.
We can create a list from the array and then use the Collections class shuffle() method to shuffle its elements. Then convert the list to the original array.
Set is unordered, so randomizing an unordered Collection doesn't make any logical sense. An ordered Set is ordered using a Comparator which means it has a fixed order, you can't shuffle it, that has no meaning as the order is determined by the Comparator or the compare() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With