Home > Enterprise >  Why should I use shuffle to return a list on return value collection? (Java)
Why should I use shuffle to return a list on return value collection? (Java)

Time:03-10

I have Collection as a return value for a method, so I thought I would simply use ArrayList and return the ArrayList. Now I've seen on the Internet that someone thinks that before returning the ArrayList, if the return value is Collection, you should do Collections.shuffle(ArrayList) first. Why? What is the purpose? Can't you just return the ArrayList directly?

CodePudding user response:

The SO question you are referring to does not suggest that you should shuffle a collection before you return it. From the naming there ("FullDeck") I would guess that it is something related to a card deck that should be shuffled for a game.

You don't need to shuffle an ArrayList before you return it as a collection, you can directly return the list - it implements the Collection interface and doesn't need any further processing to be accessed by that interface.

The shuffling is only relevant if you want to have the elements of the list in random order for some other reason.

  • Related