• 两种构造方法

    Random(); //创建一个新的随机数生成器,默认使用当前系统时间的毫秒数作为种子,一旦选中即不变,而不是根据时间改变
    Random(20); //指定种子,即随机算法的起源数字
    
  • 生成随机整数

    Random rand =new Random(25);
    int i=rand.nextInt(100); //100是上上限,[0,100)
    
  • 种子的作用:对于种子相同的Random对象,生成的随机数序列是一样的。

    public static void main(String[] args) {
        Random ran1 = new Random(10);
        System.out.println("使用种子为10的Random对象生成[0,10)内随机整数序列: ");
        for (int i = 0; i < 10; i++) {
            System.out.print(ran1.nextInt(10) + " ");
        }
    
        Random ran2 = new Random(10);
        System.out.println("使用另一个种子为10的Random对象生成[0,10)内随机整数序列: ");
        for (int i = 0; i < 10; i++) {
            System.out.print(ran2.nextInt(10) + " ");
        }
        /**
         * 输出结果为:
         * 
         * 使用种子为10的Random对象生成[0,10)内随机整数序列: 
         * 3 0 3 0 6 6 7 8 1 4 
         * 使用另一个种子为10的Random对象生成[0,10)内随机整数序列: 
         * 3 0 3 0 6 6 7 8 1 4 
         * 
         */
    }
    
  • 相同种子的Random对象,相同次数两个对象生成的随机数相同,但同个对象不同次数生成的随机数不同。
  • 只有一个Random对象,上次执行程序与下次产生的随机数不同。
  • 如果想避免出现测试数据相同的情况,则无论需要生成多少个随机数,都只是用一个Random对象即可。
  • 使用时间或自定义种子都很容易生成重复的随机数,可借助数组和集合类剔除重复数
//生成 [0-n) 个不重复的随机数
public ArrayList getDiffNO(int n){
    ArrayList list = new ArrayList(); //list 用来保存这些随机数
    Random rand = new Random();
    boolean[] bool = new boolean[n]; //默认初始值为false
    int num = 0;
    //开始产生随机数
    for (int i = 0; i < n; i++) {
        do {
            //如果产生的数相同继续循环
            num = rand.nextInt(n);
        } while (bool[num]); //第一个肯定是false,不会循环的
        bool[num] = true;
        list.add(num);
    }
    return list;
}

方法简介

  • protected int next(int bits):生成下一个伪随机数(其随机算法实际是有规则的,故称为伪随机)。
  • boolean nextBoolean():返回下一个伪随机数,false或true。
  • void nextBytes(byte[] bytes):生成随机字节并将其置于用户提供的 byte 数组中。若Random对象时同一个,则每次生成的数组都相同。

    public static void main(String[] args) {
        byte[] bytes=new byte[10];
        Random random=new Random(); //加不加种子、加什么种子都一样
        random.nextBytes(bytes);
        System.out.println(bytes); //每次调用生成的数组都一样
    
        //下面这一块产生的数组也和上面一样
        Random random2=new Random();
        random2.nextBytes(bytes);
        System.out.println(bytes);
    }
    
  • double nextDouble():[0.0,1.0)之间均匀分布的 double值。
  • float nextFloat():[0.0,1.0)之间均匀分布float值。
  • double nextGaussian():返回下一个伪随机数,它是取自此随机数生成器序列的、呈高斯(“正态”)分布的double值,其平均值是0.0标准差是1.0。即一个double型的Gaussian值。
  • int nextInt():随机 int 值,[-2^31,2^31-1]。
  • int nextInt(int n):返回指定上限的随机int值。
  • long nextLong():随机 long 值。
  • void setSeed(long seed):设置种子。
  • 生成[0,5.0)区间的小数:double d2 = r.nextDouble() * 5;
  • 生成[1,2.5)区间的小数:先把左区间减到0,double d3 = r.nextDouble() * 1.5 + 1;
  • 生成[0,10)区间的整数:     
    int n2 = r.nextInt(10);//方法一
    
        n2 = Math.abs(r.nextInt() % 10);//方法二

更多推荐

Java随机数生成器-Random类