开发者

How can I shuffle a specific range of an ArrayList?

开发者 https://www.devze.com 2023-03-28 23:31 出处:网络
In Java, I know that to shuffle an ArrayList, the method Collections.shuffle() exists, however this shuf开发者_Python百科fles the entire list.

In Java, I know that to shuffle an ArrayList, the method Collections.shuffle() exists, however this shuf开发者_Python百科fles 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));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号