Random 类有一个方法可以在给定范围内生成随机 int。例如:
Random r = new Random();
int x = r.nextInt(100);
这将生成一个大于或等于 0 且小于 100 的 int 数字。我想对 long 数字执行完全相同的操作。
long y = magicRandomLongGenerator(100);
Random 类只有 nextLong(),但不允许设置范围。
最佳答案
从Java 7(或Android API Level 21 = 5.0+)开始,您可以直接使用ThreadLocalRandom.current().nextLong(n)
(对于0 ≤ x < n) 和 ThreadLocalRandom.current().nextLong(m, n)
(对于 m ≤ x < n)。请参阅@Alex详细回答。
如果您无法使用Java 6(或Android 4.x),则需要使用外部库(例如org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator( ).nextLong(0, n-1)
,请参阅 @mawaldne 的答案),或实现您自己的 nextLong(n)
。
根据Random
documentation , nextInt
实现为
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException("bound must be positive");
if ((bound & -bound) == bound) // i.e., bound is a power of 2
return (int)((bound * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % bound;
} while (bits - val + (bound-1) < 0);
return val;
}
因此我们可以修改它来执行nextLong
:
long nextLong(Random rng, long bound) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % bound;
} while (bits-val+(bound-1) < 0L);
return val;
}
关于Java:0 <= x < n 范围内的随机长数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564561/