1. matt:

    Thanks so much Ryan, this helped a ton.

    April 26, 2010 at 10:34 pm |
  2. Bhagyashree:

    Thanks a lot for this!!

    June 29, 2010 at 9:41 am |
  3. Sekol:

    Collections.shuffle(Arrays.asList(array)); doesnt work for int arrays, probably because it isnt Object. Be aware of it!

    January 21, 2011 at 10:05 am |
  4. Mike:

    “>” should be replaced with “<" in the first code sample.

    June 13, 2011 at 8:04 am |
  5. Stanley:

    Thanks, pal. Collections.shuffle helped a lot…

    July 1, 2011 at 1:44 pm |
  6. Habib:

    True, it does not work, but if you’re trying to shuffle an array of int, instead declaring:

    int[] array = new array[]{1,2,3}

    Use an integer object:

    Integer[] array = new Integer[]{1,2,3}

    Works with Double, Float, etc..

    July 29, 2011 at 11:29 pm |
  7. Vu:

    There is no hand-holding tutorial for this because it can easily be achieved with a loop and an RNG. I don’t know why there is the .shuffle() method for List but not for Array, though. Java is known for its extensive library, there should be tool for every tiny thing in this universe, in my opinion.

    Nice laptop by the way. Really jealous of you.

    August 23, 2011 at 4:36 am |
  8. samusb:

    the hard method is wrong this part:
    for (int i=0; i > cards.length; i++)

    and the correct form is :
    for (int i=0; i is wrong, it should be <

    just click the java:shuffling link and you will see

    February 7, 2012 at 3:23 am |
  9. John White:

    This has helped me so much Ryan, I could kiss you!

    February 23, 2012 at 11:24 pm |
  10. Ken Arnold:

    Nice post, but I have to say that your “hard” code makes a common error. Because that is the fast loop to use, it’s probably a good idea to correct the post, especially since this article is the top google hit for “java shuffle array”. It’s an easy error to make, I made it in my first card game, and it was explained to me thusly:

    When you choose a value to swap with, you must choose from the unshuffled parts of the array, not including already shuffled values:

    int randomPosition = i + rgen.nextInt(cards.length – i);

    It’s funny, it doesn’t seem like this should matter. It’s random in either case, right?

    I can’t describe exactly how it goes wrong but you can prove it’s wrong anyway.

    Let’s say you are shuffling 4 values. There are 4! possible orders. 4! = 4 * 3 * 2 * 1 = 24.

    If instead you pick *any* element to swap with (as in the original code) including already-shuffled values, there are 4^4 possibilities. 4^4 = 256

    Note that 256 is not a multiple of 24.

    So there cannot be an even distribution of the actual 4! possibilities within 4^4 outputs. So the 4^4 algorithm (as in your original code) cannot be producing all 4! possibilities with equal probability.

    February 27, 2012 at 3:56 am |