如何在特定范围内生成随机int值?
以下方法存在与整数溢出相关的错误:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
使用Java 8 Streams,
传递初始容量-多少个数字将randomBound从x传递到randomBoud是否为已排序传递true/false传递新的Random()对象
public static List<Integer> generateNumbers(int initialCapacity, int randomBound, Boolean sorted, Random random) {
List<Integer> numbers = random.ints(initialCapacity, 1, randomBound).boxed().collect(Collectors.toList());
if (sorted)
numbers.sort(null);
return numbers;
}
在本例中,它从1-Randombound生成数字。