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
如果您使用 Java 6(或 Android 4.x),您需要使用外部库(例如 org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator( ).nextLong(0, n-1)
,见 @mawaldne 的回答),或者实现你自己的 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;
}
关于Java:0 <= x < n 范围内的随机长数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2546078/