简体   繁体   English

如何随机播放 ArrayList 的特定范围?

[英]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.在 Java 中,我知道要对 ArrayList 进行洗牌,方法 Collections.shuffle() 存在,但是这会洗牌整个列表。

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:使用List.subListCollections.shuffle ,像这样:

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.) (注意subList排他的第二个索引,所以如果你想在 shuffle 中包含end索引,请使用end+1 。)

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.由于List.subList返回列表的视图,因此(通过 shuffle 方法)对子列表所做的更改也会影响原始列表。

Yes - use List.sublist(start, end) and Collections.shuffle() that, ie:是 - 使用List.sublist(start, end)Collections.shuffle() ,即:

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 sublist返回列表的视图,所以当你打乱它时,你打乱了实际的列表,但只在开始和结束之间

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

Note the +1, because the end index of subList() is exclusive.注意 +1,因为subList()的结束索引是独占的。

It's simple这很简单

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM