Random class has a method to generate random int in a given range. For example:
Random r = new Random();
int x = r.nextInt(100);
This would generate an int number more or equal to 0 and less than 100. I'd like to do exactly the same with long number.
long y = magicRandomLongGenerator(100);
Random class has only nextLong(), but it doesn't allow to set range.
From the page on Random:
So if you want to get a
Long
, you're already not going to get the full 64 bit range.I would suggest that if you have a range that falls near a power of 2, you build up the
Long
as in that snippet, like this:to get a 35 bit range, for example.
//use system time as seed value to get a good random number
//Loop until get a number greater or equal to 0 and smaller than n
The methods using the
r.nextDouble()
should use:Starting from Java 7 (or Android API Level 21 = 5.0+) you could directly use
ThreadLocalRandom.current().nextLong(n)
(for 0 ≤ x < n) andThreadLocalRandom.current().nextLong(m, n)
(for m ≤ x < n). See @Alex's answer for detail.If you are stuck with Java 6 (or Android 4.x) you need to use an external library (e.g.
org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1)
, see @mawaldne's answer), or implement your ownnextLong(n)
.According to http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html
nextInt
is implemented asSo we may modify this to perform
nextLong
:Further improving kennytm's answer: A subclass implementation taking the actual implementation in Java 8 into account would be:
From Java 8 API
It could be easier to take actual implementation from API doc https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#longs-long-long-long- they are using it to generate longs stream. And your origin can be "0" like in the question.