最近抓取新浪微博的数据,需要产生一些随机微博的ID。由于新浪微博的ID是一个16位的数字,所以在Java程序中要用long型来产生。并且,微博ID是有一定范围的,如果不限定范围,命中的概率会很低。这里就需要限定产生随机数的范围。然而,在Java SDK中,只提供了一个产生整数的、可限定范围的方法:
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;
}
看了一下官方文档,并到网上查阅了一些资料。认为如下实现是最好的获得限制范围的long型数字的方法:
public 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;
}