Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Collections.Shuffle on only part of an array Java

Tags:

java

arrays

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 a part of the array rather than the whole thing? I am making quite a simple program so I would like to keep using the Collections class however all solutions are welcome. Thanks

like image 764
user3456 Avatar asked Jan 13 '16 22:01

user3456


2 Answers

You can use the List type's subList method to get a List object with a view of a particular range of elements from the original list. I haven't tested this, but I think it should work:

Collections.shuffle(Arrays.asList(randomList).subList(startIndex, endIndex));
like image 186
templatetypedef Avatar answered Oct 24 '22 13:10

templatetypedef


You can also try the below. However, more cleaner code would be as suggested by templatetypedef. 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 memory leak issue with Sublist in arrays. Not sure if that got rectified. If someone can provide any useful information regarding that would be great. Remember specifically calling value in between the List will cause IndexOutOfBoundsIssue(). That should be handled.

like image 29
Anvesh Vejandla Avatar answered Oct 24 '22 13:10

Anvesh Vejandla