CodeGuy
CodeGuy

Reputation: 28907

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)

Upvotes: 16

Views: 3596

Answers (4)

aioobe
aioobe

Reputation: 420951

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.

Upvotes: 25

adarshr
adarshr

Reputation: 62573

It's simple

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

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

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

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

Upvotes: 2

Bohemian
Bohemian

Reputation: 424983

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

Upvotes: 8

Related Questions