Setting a seed to shuffle ArrayList in Java deterministically

前端 未结 3 645
一向
一向 2021-01-07 17:13

I have a list of integers (currently using cern.colt.list.IntArrayList). I can call \"shuffle()\" and randomly shuffle them. I would like to be able to reproduce a shuffle.

相关标签:
3条回答
  • 2021-01-07 17:52

    there is an alternative method which takes a Random as source

    0 讨论(0)
  • 2021-01-07 17:54

    This is possible by using the shuffle method that allows you to provide the backing Random instance: Collections.shuffle(List<?> list, Random rnd):

    Example:

    Collections.shuffle(yourList, new Random(somePredefinedSeed));
    
    0 讨论(0)
  • 2021-01-07 18:06

    You can specify the Random instance with a seed value using public static void shuffle(List list, Random rnd). For the Random(long seed) constructor you can specify a seed.

    From Java Docs:

    Randomly permute the specified list using the specified source of randomness. All permutations occur with equal likelihood assuming that the source of randomness is fair.

    0 讨论(0)
提交回复
热议问题