random number with seed

后端 未结 6 1181
暗喜
暗喜 2021-01-05 15:35

Reference: link text

i cannot understand the following line , can anybody provide me some example for the below statement?

If two instances of Random are cre

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 15:48

    Since you asked for an example:

    import java.util.Random;
    public class RandomTest {
        public static void main(String[] s) {
            Random rnd1 = new Random(42);
            Random rnd2 = new Random(42);
    
            System.out.println(rnd1.nextInt(100)+" - "+rnd2.nextInt(100));
            System.out.println(rnd1.nextInt()+" - "+rnd2.nextInt());
            System.out.println(rnd1.nextDouble()+" - "+rnd2.nextDouble());
            System.out.println(rnd1.nextLong()+" - "+rnd2.nextLong());
        }
    }
    

    Both Random instances will always have the same output, no matter how often you run it, no matter what platform or what Java version you use:

    30 - 30
    234785527 - 234785527
    0.6832234717598454 - 0.6832234717598454
    5694868678511409995 - 5694868678511409995
    

提交回复
热议问题