如何在特定范围内生成随机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`.

当前回答

int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();

或者看看Apache Commons的RandomUtils。

其他回答

ThreadLocalRandom相当于多线程环境的java.util.Random类。在每个线程中本地执行随机数的生成。因此,通过减少冲突,我们可以获得更好的性能。

int rand = ThreadLocalRandom.current().nextInt(x,y);

x、 y-间隔,例如(1,10)

范围[最小值最大值](含)内的随机数:

int randomFromMinToMaxInclusive = ThreadLocalRandom.current()
        .nextInt(min, max + 1);

你可以使用

RandomStringUtils.randomNumeric(int count)

该方法也来自Apache Commons。

这将生成范围(最小值-最大值)不重复的随机数列表。

generateRandomListNoDuplicate(1000, 8000, 500);

添加此方法。

private void generateRandomListNoDuplicate(int min, int max, int totalNoRequired) {
    Random rng = new Random();
    Set<Integer> generatedList = new LinkedHashSet<>();
    while (generatedList.size() < totalNoRequired) {
        Integer radnomInt = rng.nextInt(max - min + 1) + min;
        generatedList.add(radnomInt);
    }
}

希望这对你有所帮助。

只需使用Random类:

Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);