随机产生一个限定范围的long型数字

最近抓取新浪微博的数据,需要产生一些随机微博的ID。由于新浪微博的ID是一个16位的数字,所以在Java程序中要用long型来产生。并且,微博ID是有一定范围的,如果不限定范围,命中的概率会很低。这里就需要限定产生随机数的范围。然而,在Java SDK中,只提供了一个产生整数的、可限定范围的方法:

[java] view plain copy
  1. public int nextInt(int n) {  
  2.      if (n<=0)  
  3.                 throw new IllegalArgumentException("n must be positive");  
  4.   
  5.      if ((n & -n) == n)  // i.e., n is a power of 2  
  6.          return (int)((n * (long)next(31)) >> 31);  
  7.   
  8.      int bits, val;  
  9.      do {  
  10.          bits = next(31);  
  11.          val = bits % n;  
  12.      } while(bits - val + (n-1) < 0);  
  13.      return val;  
  14.  }  

看了一下官方文档,并到网上查阅了一些资料。认为如下实现是最好的获得限制范围的long型数字的方法:
[java] view plain copy
  1. public long nextLong(Random rng, long n) {  
  2.    // error checking and 2^x checking removed for simplicity.  
  3.    long bits, val;  
  4.    do {  
  5.       bits = (rng.nextLong() << 1) >>> 1;  
  6.       val = bits % n;  
  7.    } while (bits-val+(n-1) < 0L);  
  8.    return val;  

你可能感兴趣的:(java基础)