开发者

Collections.shuffle(List list)

What will开发者_运维百科 prompt one to use this method?

Update : I see the point now. I like the reason of Uri "Shuffling is not a trivial algorithm". That is quite true.


There can be many reasons one would want to randomly shuffle an ordered sequence of elements. For instance, a deck of cards.

Shuffling is not a trivial algorithm, just as sorting isn't - So it is common enough to necessitate a library function.

As to why a list - obviously it has to be an ordered collection, thus not any general Collection. Only list and its subtypes are guaranteed to be ordered. The Collections class does not provide operations for arrays, but you could (and probably should, for performance) pass an ArrayList to this method.


Um, if you have a collection, and you want to shuffle it...

The most obvious example would be a card game, where you have objects representing individual cards, and a collection representing the deck which you want to shuffle.

Another example might be if you're presenting the user with multiple answers in a questionnaire, and you don't want there to be any bias due to the ordering of the answers - so you present each user a shuffled set of answers to pick from.


Well, imagine you're modeling a deck of cards. Shuffle would be one of the first functions you'd write.

Anytime you'd want to randomize the contents of a collection, you'd use shuffle.


Some ideas how you could use this method:

  • Shuffle cards in a game
  • Randomize an array in a test case for a sorting algorithm
  • Shuffling test cases in your test suite to make sure they don't depend on each other
  • If you try to solve an NP-complete problem like the traveling salesman, one approach is to take the input, shuffle it several times and then use the result with the shortest length. This gives you a solution which runs in O(N) time (where N is the number of nodes).
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜