如何在特定范围内生成随机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 IntStream和Collections.shuffle的不同方法
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
IntStream range = IntStream.rangeClosed(5,10);
ArrayList<Integer> ls = new ArrayList<Integer>();
//populate the ArrayList
range.forEach(i -> ls.add(new Integer(i)) );
//perform a random shuffle using the Collections Fisher-Yates shuffle
Collections.shuffle(ls);
System.out.println(ls);
}
}
Scala中的等价项
import scala.util.Random
object RandomRange extends App{
val x = Random.shuffle(5 to 10)
println(x)
}
Java 17引入了RandomGenerator接口,它提供了一个int nextInt(int origin,int bound)方法来获取范围内的随机整数:
// Returns a random int between minimum (inclusive) & maximum (exclusive)
int randomInt = RandomGenerator.getDefault().nextInt(minimum, maximum);
除了用于Java17中添加的新的随机生成算法之外,该接口还添加到现有的随机生成类(random、SecureRandom、SplitableRandom和ThreadLocalRandom)中。因此,从Java 17开始,这些类具有以下有界nextInt方法:
new Random().nextInt(minimum, maximum);
new SecureRandom().nextInt(minimum, maximum);
new SplittableRandom().nextInt(minimum, maximum);
new ThreadLocalRandom().nextInt(minimum, maximum);
从Java17开始,这种方法是Random和SecureRandom的新方法。在Java17之前,ThreadLocalRandom和SplitableRandom已经有了这个方法,尽管它不是由共享接口指定的。