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.
ThreadLocalRandom
ThreadLocalRandom
has anextLong(long bound)
method.It also has
nextLong(long origin, long bound)
if you need an origin other than 0. Pass the origin (inclusive) and the bound (exclusive).SplittableRandom
has the samenextLong
methods and allows you to choose a seed if you want a reproducible sequence of numbers.How about this:
?
The below Method will Return you a value between 10000000000 to 9999999999
The methods above work great. If you're using apache commons (org.apache.commons.math.random) check out RandomData. It has a method: nextLong(long lower, long upper)
http://commons.apache.org/math/userguide/random.html
http://commons.apache.org/math/api-1.1/org/apache/commons/math/random/RandomData.html#nextLong(long,%20long)
Use the '%' operator
By using the '%' operator, we take the remainder when divided by your maximum value. This leaves us with only numbers from 0 (inclusive) to the divisor (exclusive).
For example:
The standard method to generate a number (without a utility method) in a range is to just use the double with the range:
will give you a long between 0 (inclusive) and range (exclusive). Similarly if you want a number between x and y:
will give you a long from 1234567 (inclusive) through 123456789 (exclusive)
Note: check parentheses, because casting to long has higher priority than multiplication.