Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Collections API to Shuffle

I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.

Lets say that I am trying to shuffle the randomizer array.

int[] randomizer = new int[] {200,300,212,111,6,2332}; 
Collections.shuffle(Arrays.asList(randomizer));

For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas?

like image 824
101010110101 Avatar asked Oct 08 '08 00:10

101010110101


People also ask

Is shuffle available in collections class?

shuffle() method of Collections class as the class name suggests is present in utility package known as java. util that shuffles the elements in the list.

What is collection shuffle?

shuffle method is defined in Java's built-in java. util. Collections class. As its name suggests, the method​ shuffles the elements of a given list by randomly permuting them.

How do you shuffle elements in an ArrayList?

In order to shuffle elements of ArrayList with Java Collections, we use the Collections. shuffle() method.


1 Answers

Arrays.asList cannot be used with arrays of primitives. Use this instead:

Integer[] randomizer = new Integer[] {200,300,212,111,6,2332}; 
Collections.shuffle(Arrays.asList(randomizer));

The same rule applies to most classes in the collections framework, in that you can't use primitive types.

The original code (with int[]) compiled fine, but did not work as intended, because of the behaviour of the variadic method asList: it just makes a one-element list, with the int array as its only member.

like image 175
Chris Jester-Young Avatar answered Sep 28 '22 01:09

Chris Jester-Young