请问Random中的nextInt()和nextInt(int n)的区别是什么?nextInt(100) 可以产生100以内的随机数而用nextInt()也可以呀:
Random random = new Random();
int a = (random.nextInt(100) >>> 1) % 100;那他们有什么区别,用于什么不同的情况?
Random random = new Random();
int a = (random.nextInt(100) >>> 1) % 100;那他们有什么区别,用于什么不同的情况?
int nextInt()
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. 我觉得从效果上没有大的区别,内在实现不同。
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;
}public int nextInt() { return next(32); }
这是源代码,看看就知道有什么不同了。
但是nextInt(n)是从0到n的随机数
import java.util.*;
import java.io.*;
nextInt(n) [0, n-1]