Collections.shuffle (List of Lists)

What prompts you to use this method?

Update . Now I see it. I like Uri's reason "Shuffling is not a trivial algorithm." It's true.

+6
java collections shuffle
source share
4 answers

There can be many reasons why you could randomly shuffle an ordered sequence of elements. For example, a deck of cards.

Shuffling is not a trivial algorithm, since sorting is not - therefore, it is enough to spread the need for a library function.

As for why the list is, obviously, it should be an ordered collection, not some kind of general collection. Only the list and its subtypes are guaranteed. The Collections class does not provide operations for arrays, but you can (and probably should, for performance) pass an ArrayList to this method.

+12
source share

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

The most obvious example is a card game in which you have objects representing individual cards and a set representing the deck you want to shuffle.

Another example would be if you submit several answers to the user in the questionnaire, and you do not want to have any errors due to ordering answers, so you present each user with a shuffled set of answers to choose from.

+5
source share

Well, imagine you are modeling a deck of cards. Shuffle will be one of the first features you'll write.

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

+1
source share

Some ideas how you could use this method:

  • Shuffle cards in the game
  • Randomize an array in a test case for a sorting algorithm
  • Shuffle the test cases in your test suite to make sure they are independent of each other.
  • If you try to solve an NP-complete problem, such as a 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 that runs in O (N) time (where N is the number of nodes).
+1
source share

All Articles