3

I was reading java.util.Random class and noticed that there is no nextDouble(), nextFloat() and nextLong() which can accept a bound.

There are many way to get it done like this.

But my question is why java did not provide us with these required method like nextInt(int n) which accept the bound.

Is there any specific reason they did not provide these methods?

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
  • 2
    The title is incorrect. There are, but you have to do the boundery yourself. – AxelH May 31 '17 at 07:26
  • Think about it this way: all of the RNG numbers are basically 0-1, but generating a random int from 0-1 wouldn't really be beneficial (and casting a #nextDouble to int every time would be silly). Thus, `#nextInt(int n)`. – Rogue May 31 '17 at 07:52

2 Answers2

4

A good API always tries to provide the essential elements that a user needs to do his job.

Having nextInt(int n) is just one possible implementation. What if you need other distributions?!

In other words: the Random API could try to anticipate all potential usage patterns, but that would very much bloat the whole API. Instead, the designers choice a very small interface - but you got all the elements required to build your own things on top of that.

Thing is: in the end, this is a design style decision by the people who created the Random class. And as so often, problems could be solved in many different ways. Thus you shouldn't draw deep conclusions on the solution that was picked here.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

Looking at the code from Random.java (in jdk 8) there are two statements that stand out.

 * The algorithm is slightly tricky.  It rejects values that would result
 * in an uneven distribution (due to the fact that 2^31 is not divisible
 * by n). The probability of a value being rejected depends on n.

and

 * Linear congruential pseudo-random number generators such as the one
 * implemented by this class are known to have short periods in the
 * sequence of values of their low-order bits.

Without being an expert in random number generation (they refer to it as pseudo random number generation), it seems evident that the algorithm is trying to to a better job of returning "random" numbers than if you simply did next() % bound, in terms of randomness (and possibly also efficiency).

There is also the convenience factor but that doesn't seem to be the primary reason, given the comments in the code.

vikingsteve
  • 38,481
  • 23
  • 112
  • 156