如何订购随机数列表……
public static void method2() throws Exception {
Random rng = new SecureRandom();
Set numbers = new HashSet<>();
while (numbers.size() < 3) {
// number only added if not already present in Set, set values are unique
numbers.add(rng.nextInt(MAX));
}
List numberList = new ArrayList<>(numbers);
Collections.sort(numberList);
// lower random at index 0, mid at index 1
// you can guess where the other one is hiding
System.out.println(numberList);
}
我先把它们放在一套,以确保没有重复.当然,如果MAX的值为1,则可能需要一段时间.
这种方法的一个优点是数字应该很好地分布在0到MAX之间.如果直接使用范围,则必须处理上限和下限.
当然,只要最大值(明显)高于列表中的数字量(在这种情况下仅为3),这种方法也可以很容易地扩展到范围内工作.