Random.nextInt()是java.util.Random类中的方法。
其源码:
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException(BadBound);
int r = next(31);
int m = bound - 1;
if ((bound & m) == 0) // i.e., bound is a power of 2
r = (int)((bound * (long)r) >> 31);
else {
for (int u = r;
u - (r = u % bound) + m < 0;
u = next(31))
;
}
return r;
}
其返回随机值在0-(n-1)区间内分布。
Math.random()是math工具类中的产生随机数的方法。
其源码:
public static double random() {
return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
private static final class RandomNumberGeneratorHolder {
static final Random randomNumberGenerator = new Random();
}
public double nextDouble() {
return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
}
源码可知是Math.random调用Random的nextDouble方法。其返回值范围是0-(2)
效率上:测试代码
public static void main(String[] args){
Test test = new Test();
System.out.println("Math.random()一百万次时间:"+test.random1()+"ms");
System.out.println("random.nextInt一百万次时间:"+test.random2()+"ms");
}
int random1(){
long start = System.currentTimeMillis();
System.out.println("start"+System.currentTimeMillis());
for (int i = 0;i<1000000;i++) {
int ran = (int)(Math.random()*1000);
}
long end = System.currentTimeMillis();
System.out.println("end"+System.currentTimeMillis());
return (int) (end-start);
}
int random2(){
Random random = new Random();
long start = System.currentTimeMillis();
System.out.println("start"+System.currentTimeMillis());
for (int i = 0;i<1000000;i++) {
int ran = (int)(random.nextInt(1000));
}
long end = System.currentTimeMillis();
System.out.println("end"+System.currentTimeMillis());
return (int) (end-start);
}
结果:
start1561973201713
end1561973201768
Math.random()一百万次时间:54ms
start1561973201768
end1561973201796
random.nextInt一百万次时间:28ms
效率上使用Random.nextInt()会比Math.random快,使用时间只占后者50%到80%的时间