从Java 7(或Android API级别21 = 5.0 +)开始,您可以直接使用(对于0≤ x < n)和(对于m ≤ x < n)。有关详细信息,请参阅@Alex的答案。ThreadLocalRandom.current().nextLong(n)
ThreadLocalRandom.current().nextLong(m, n)
如果您坚持使用Java 6(或Android 4.x),则需要使用外部库(例如,请参阅@mawaldne的答案),或者实现自己的。org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1)
nextLong(n)
根据 https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html 实施为nextInt
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
因此,我们可以对其进行修改以执行:nextLong
long nextLong(Random rng, long n) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits-val+(n-1) < 0L);
return val;
}