Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shuffling Arrays (or other Collection)

 
Martin Clifford
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!
I know this mihgt be a stupid question, but I haven't been able to find it throughout all the API's.
Is there a class/method that can shuffle an array of elements into a random order? Or has anyone come up with an algorithm/method to do so? Thanks in advance!
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For a collection coll:
Collections.shuffle(coll);
For an Object[] array arr:
Collections.shuffle(Collections.asList(arr));
For an array of primitives, you'd have to replace it with an array or Object wrappers first - or write your own version of shuffle() which works for the desired primitive type.
 
Martin Clifford
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim, thanks for the reply!
However, as I'm still new to Collections, and Polymorphism as well, I don't know which collection closely resembles arrays (i.e., being able to loop through elements to check for values).
Basically, I want to shuffle an array, then check to see if the array is in numerical order. Sort of a probability thing. I've come close, and have since posting even come up with my own algorithm for shuffling a primitive array, but my method does not preserve the unique integers (as Random things sometimes don't).
Do you think you might be able to provide a sample of shuffling an array with the Collections.shuffle() method? Thanks!
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, as I'm still new to Collections, and Polymorphism as well, I don't know which collection closely resembles arrays (i.e., being able to loop through elements to check for values).
Well, you can loop through any Collection. Since the order is important, we want a List of some sort, and the shuffle() method works best for a collection which implements RandomAccess as well. ArrayList would be a good choice among the standard collections - however Arrays.asList() is even easier to use in this case. See the documentation for each of these methods/classes for more info.
Do you think you might be able to provide a sample of shuffling an array with the Collections.shuffle() method? Thanks!
Well, I already did - but to make it more explicit:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic