new Random(x)
just creates the Random
object with the given seed, it does not ifself yield a random value.
I presume you are asking what the difference is between nextInt() % x
and nextInt(x)
.
The difference is as follows.
nextInt(x)
nextInt(x)
yields a random number n where 0 ≤ n < x, evenly distributed.
nextInt() % x
nextInt() % x
yields a random number in the full integer range1, and then applies modulo x. The full integer range includes negative numbers, so the result could also be a negative number. With other words, the range is −x < n < x.
Furthermore, the distribution is not even in by far the most cases. nextInt()
has 232 possibilities, but, for simplicity's sake, let's assume it has 24 = 16 possibilities, and we choose x not to be 16 or greater. Let's assume that x is 10.
All possibilities are 0, 1, 2, …, 14, 15, 16. After applying the modulo 10, the results are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5. That means that some numbers have a greater likelihood to occur than others. That also means that the change of some numbers occurring twice has increased.
As we see, nextInt() % x
has two problems:
- Range is not as required.
- Uneven distribution.
So you should definetely use nextInt(int bound)
here. If the requirement is get only unique numbers, you must exclude the numbers already drawn from the number generator. See also Generating Unique Random Numbers in Java.
1 According to the Javadoc.