开发者

Randomizing elements position into Array

I have a array of 4 elements. I need to randomize there position. What will 开发者_如何学编程be best way to do it in Java.


You can use the following

Collections.shuffle(Arrays.asList(myArrayOfWhatever));

Then you convert your List back into an Array. This might be bad if you have an array of a very large size, but yours is only 4.

source: http://www.velocityreviews.com/forums/t302430-random-sorting-of-an-array.html (by googling [java array random sort] or [java array shuffle])


A common algorithm for shuffling is the Fisher-Yates shuffle. The wikipedia page has all the details needed


For a lot of simple tasks like this, you'll find that there are often static methods to help you - either on the collections classes themselves, or on the "plural classes" - e.g. Arrays, Collections, etc.

(Also, note that Java 7 introduces several new plural classes with useful methods on them, such as Objects and Paths).

When looking to do something simple, stop and think if there's an existing helper method before going off and implementing a homebrew solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜