What is the use of the Random(long) constructor?

前端 未结 5 2184
我寻月下人不归
我寻月下人不归 2021-01-22 04:04

There are 2 constructors of Random class

  1. public Random()
  2. public Random(long seed)

The description fo

5条回答
  •  没有蜡笔的小新
    2021-01-22 04:14

    The Random generator is a Pseudorandom number generator. That means that it is, in fact, not a random number generator but only some clever algorithm that produces fully deterministic numbers that just look like random.

    When the generator is used, each time it produces a random number it modifies its internal state in order to produce a different number at the next call. However, at the beginning the internal state of this algorithm must be initialised, and the value that is used for this initialisation is commonly called seed. The parameterless constructor makes a seed on its own, based on system time, while the other constructor lets you to put your seed, which allows you to make it repeatable - the same seed (and the same generator) will produce the same sequence of numbers.

    If you are interested, here is the source code of the Random class from OpenJDK (i.e. the open source implementation of Java, but it should be functionally equivalent). The constructor with seed is at line 135, the setSeed method is at line 168 and e.g. the nextInt method is at line 328 which just calls a private method next which is at line 198 and which is where all the magic happens. It also has javadoc with the reference to the (probably more mathematical) description of this kind of generator.

提交回复
热议问题