Reputation: 2101
dI got a little question about the Collections.shuffle() method.
Case:
I have 2 lists I need to shuffle, then union / merge them into one list, then shuffle the new complete list. I have used the shuffle method with the Random class - using system.nanoTime() as seed.
Code looks as below:
public List<PresentationArticle> shuffleUnionShuffleLists(List<PresentationArticle> list1, List<PresentationArticle> list2) {
shuffleList(list1);
shuffleList(list2);
List<PresentationArticle> resultList = //merge/union the two lists
shuffleList(resultList);
return resultList;
}
public void shuffleList(List<PresentationArticle> articleList) {
long seed = System.nanoTime();
Collections.shuffle(articleList, new Random(seed));
}
My question is: Will this be a proper random shuffling of the lists, when the methods runs right after eachother, with a new Random object and a new (but almost identical) seed?
The method shuffleUnionShuffleLists()
will be run approximately every 3 minutes.
Upvotes: 0
Views: 1307
Reputation: 73528
First of all, you don't generally create a new Random object for every invocation. It doesn't make it "more random". Secondly, shuffling several times doesn't increase entropy either, so a single shuffle is all that is needed.
Upvotes: 0
Reputation: 533472
The default seed is based on nanoTime and a counter, so it is slightly more random than what you have. Also there is no need to shuffle more than once. Once it is randomized doing it more than once just takes longer.
So in your case, all you need to do is add the two list together and shuffle that using a new Random()
, or reusing an old one.
public List<PresentationArticle> shuffleUnionShuffleLists(List<PresentationArticle> list1, List<PresentationArticle> list2) {
List<PresentationArticle> list = new ArrayList<>(list1.size()+list2.size());
list.addAll(list1);
list.addAll(list2);
Collections.shuffle(list);
return list;
}
Also it is usually best not to modify arguments passed to you.
Upvotes: 2
Reputation: 65793
There's no reason I can think of to shuffle the lists before merging. Randomising/shuffling something twice does not make them any more random.
Will this be a proper random shuffling of the lists
Yes but you are doing too much.
Upvotes: 0