所以我有以下数组:
String [] randomList = new String [16];
randomList[0]="Dog";
randomList[1]="Dog";
randomList[2]="Cat";
randomList[3]="Cat";
randomList[4]="Mouse";
randomList[5]="Mouse";
randomList[6]="Car";
randomList[7]="Car";
randomList[8]="Phone";
randomList[9]="Phone";
randomList[10]="Game";
randomList[11]="Game";
randomList[12]="Computer";
randomList[13]="Computer";
randomList[14]="Toy";
randomList[15]="Toy";
我只想打乱这个数组的前9个元素。我使用了以下代码,但它打乱了整个数组。
Collections.shuffle(Arrays.asList(randomList));
如何只打乱数组的一部分而不是整个数组?我正在制作一个非常简单的程序,所以我想继续使用Collections类,但欢迎所有解决方案。感谢
您可以使用List
类型的subList
方法从原始列表中获取具有特定元素范围视图的List
对象。我还没有测试过,但我认为它应该有效:
Collections.shuffle(Arrays.asList(randomList).subList(startIndex, endIndex));
您也可以尝试以下操作。然而,更干净的代码将如templatepedef所建议的那样。List<String> newList = new ArrayList<String>();
for(int i=0; i<randomList.size()-ValuePreferred; i++){
newList.add(randomList.get(i));
}
Collections.shuffle(newList);
randomList.removeAll(newList);
newList.addAll(randomList);
此外,我听说Sublist在数组中存在内存泄漏问题。不确定这是否得到了纠正。如果有人能提供任何有用的信息,那就太好了。请特别记住,调用List之间的值将导致IndexOutOfBoundsIssue()。这是应该处理的。