How to call Collections.Shuffle only for part of a Java array

So, I have the following array:

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"; 

I want to shuffle only the first 9 elements of this array. I used the following code, but it shuffles the entire array.

 Collections.shuffle(Arrays.asList(randomList)); 

How would I shuffle only part of an array, not all? I am making a fairly simple program, so I would like to continue to use the Collections class, but all solutions are welcome. Thanks

+6
source share
2 answers

You can use the List type subList method to get a List object with a view of a certain range of elements from the original list. I have not tested this, but I think it should work:

 Collections.shuffle(Arrays.asList(randomList).subList(startIndex, endIndex)); 
+10
source

You can also try the following. However, cleaner code will be the same as templatetypedef suggested. 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);

Also, I hear about a memory leak issue using Sublist in arrays. Not sure if this is fixed. If someone can provide any useful information about this, it will be great. Remember that a specific call value between lists calls IndexOutOfBoundsIssue (). It must be handled.

+1
source

All Articles