6

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?

Hooked
  • 84,485
  • 43
  • 192
  • 261
101010110101
  • 1,940
  • 8
  • 31
  • 42

2 Answers2

18

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.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • good catch! i was thinking the problem was that the list would be sorted, but not the original array, but the javadocs in Arrays.asList says that the list uses the underlying array. If you grow this list you will have a problem though! (the array will get replaced with a new array) – John Gardner Oct 08 '08 at 00:58
  • Lovely... another case where Autoboxing/Unboxing doesn't work as expected (or in this case, simply doesn't apply). – James Schek Oct 08 '08 at 15:26
  • 1
    I think Josh Bloch has said that it was a mistake to use ... on asList for this very reason. – Tom Hawtin - tackline Oct 08 '08 at 19:59
0

Chris' answer is correct.

As i said in a comment on Chris' answer, your underlying array will change appropriately unless the arraylist needs to grow, and the list creates a new one and copies items into it.

You may want to keep a reference to the list and iterate over that after the Arrays.asList call, and not iterate over the array after that, iterate over the List instead.

John Gardner
  • 24,225
  • 5
  • 58
  • 76
  • While my answer is correct, unfortunately, yours isn't. :-( The list returned from `Arrays.asList` is of type `java.util.Arrays$ArrayList`, and unlike `java.util.ArrayList`, is not resizeable (an `UnsupportedOperationException` is thrown if you try). So the returned list is _always_ backed by the given array. – C. K. Young Oct 05 '11 at 16:10