Random.nextLong(long bound)?

Steven Schlansker stevenschlansker at gmail.com
Wed Oct 18 21:54:12 UTC 2017


My coworker is implementing an algorithm for which he needs a bounded random long.
He needs to be in full control of the seed and not share the instance (i.e. not use ThreadLocalRandom).

Random helpfully provides a nextInt(int bound) but nextLong has no such overload.

The code to do so is not super involved, but you only have to briefly peruse
the wasteland of StackOverflow answers to see what happens when you get developers
to solve this problem themselves:

https://stackoverflow.com/questions/2546078/java-random-long-number-in-0-x-n-range

Seems like a nextLong(bound) would be a trivial addition with outsize benefits.
Any reason not to add it?

PS --
nextLong says
"Returns the next pseudorandom, uniformly distributed {@code long} value from this random number generator's sequence."
and
"Because class {@code Random} uses a seed with only 48 bits, this algorithm will not return all possible {@code long} values."

How can this be true?  Given a long L1 which can be generated and L2 which cannot, it seems trivial that P(L1) != P(L2)
and therefore it is not a uniformly distributed long value.  Am I misunderstanding this concept?

Thanks!
Steven



More information about the core-libs-dev mailing list