tags:

views:

88

answers:

2

I have a array of integer numbers (say 1,2,3,4,5 or 1,2,3, ... 10 or 1,2,3, ... 50) from which I would like to get a random set of numbers ordered differently every time. Is there a utility method to do this?

e.g. for 1,2,3,4,5 post randomization it might be either [1,5,4,2,3 or 2,1,3,5,4 or 3,1,2,4,5 or ...]

I would like to know if there is a java utility method / class which already provides this capability?

+2  A: 

Collections.shuffle?

That won't help directly with an array, but if you convert it to a List<Integer> it'll work. (You can't use Arrays.asList with an int[], unfortunately.)

Alternatively, you can implement a Fisher-Yates Shuffle yourself very easily - in fact, that Wikipedia page even has an implementation in Java :) (I'd change it to take a Random reference as a parameter, however - you don't want to create a new instance of Random every time you call it.)

Jon Skeet
(+1) and the conversion is done using `Arrays.asList(array)` if the array is of non-primitives
Bozho
@Bozho: Thanks, fixed the `asList` reference.
Jon Skeet
and http://commons.apache.org/lang/api/org/apache/commons/lang/ArrayUtils.html can help with that - `toObject(..)`
Bozho
+1  A: 

see java.util.Collections.shuffle Your array needs to be an colletion. You can use java.util.Arrays.asList for this.

neo