java生成随机数的几种方式

267 阅读1分钟

java生成随机数

  • Math类random方法
  • Random类中很多方法
  • ThreadLocalRandom类中很多方法
  • UUID类生成UUID

Math类

Math类random()方法,返回0.0到1.0的正数随机数

示例代码:

public class App {
    public static void main(String[] args) {
        //返回0.0到1.0的正数
        double random = Math.random();
        System.out.println(random);
    }
}

结果:

image.png


Random类

  • nextInt()方法随机返回int值
  • nextInt(int n)方法返回,0(包括)和指定值(不包括)之间的随机int值

示例代码:

public class App {
    public static void main(String[] args) {
        Random random1 = new Random();
        System.out.println(random1.nextInt(5));
    }
}

结果:

image.png


ThreadLocalRandom类

ThreadLocalRandom类是Random类的子类,和Random类方法相似

nextInt(int a, int b)方法返回a到b之间的随机int值,含头不含尾

示例代码:

public class App {
    public static void main(String[] args) {
       ThreadLocalRandom current = ThreadLocalRandom.current();
       System.out.println(current.nextInt(2,5));
    }
}

结果:

image.png


UUID类

通过static UUID randomUUID()静态方法获取随机生成的UUID

示例代码:

public class App {
    public static void main(String[] args) {
       System.out.println(UUID.randomUUID().toString());
    }
}

结果:

image.png