Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a big question in my mind:

I can use a seed number to generate random numbers:

Random rand = new Random(34666666);

But the thing that I cannot understand is the role of that seed. For example what is the difference of

That code with the following:

Random rand = new Random();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
282 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you supply a specific, hard-coded seed, to the one-arg Random constructor, the random numbers that will be generated will always be the same, every time you run the program. That is needed when you need a predictable source of random numbers.

However, when you don't supply a seed, then the Random constructor will choose a seed for you, based on System.nanoTime. The random numbers will be different every time you run the program, because the seed will be different each time.

Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

This is important because Java's random number generator is pseudo-random; each new pseudo-random number affects the seed that is used for the next pseudo-random number that gets generated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...