Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I shuffle a specific range of an ArrayList?

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)
like image 494
CodeGuy Avatar asked Aug 16 '11 14:08

CodeGuy


People also ask

How do you shuffle values in an ArrayList?

In order to shuffle elements of ArrayList with Java Collections, we use the Collections. shuffle() method.

Can you shuffle an ArrayList Java?

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.

Can you shuffle a set in Java?

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.


1 Answers

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.

like image 132
aioobe Avatar answered Sep 21 '22 15:09

aioobe