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?
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 useArrays.asListwith anint[], 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
Randomreference as a parameter, however – you don’t want to create a new instance ofRandomevery time you call it.)