16

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)
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
CodeGuy
  • 28,427
  • 76
  • 200
  • 317

4 Answers4

25

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
8

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

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2
Collections.shuffle(list.subList(start, end+1));

Note the +1, because the end index of subList() is exclusive.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

It's simple

public void shuffleArrayListInTheRange(int start, int end) {
    Collections.shuffle(list.subList(start, end));
}
adarshr
  • 61,315
  • 23
  • 138
  • 167