Java Random类有哪些常用方法

发布时间:2025-02-12 13:54:06 作者:小樊
来源:亿速云 阅读:94

java.util.Random 类在 Java 中被广泛用于生成随机数。以下是 Random 类中一些常用的方法:

  1. nextInt(): 生成一个介于 0(包括)和指定整数(不包括)之间的随机整数。

    int randomInt = random.nextInt();
    int randomIntInRange = random.nextInt(upperBound);
    
  2. nextInt(int bound): 生成一个介于 0(包括)和指定整数(不包括)之间的随机整数。

    int randomInt = random.nextInt(10); // 生成 0 到 9 之间的随机整数
    
  3. nextLong(): 生成一个介于 0(包括)和指定长整数(不包括)之间的随机长整数。

    long randomLong = random.nextLong();
    long randomLongInRange = random.nextLong(upperBound);
    
  4. nextDouble(): 生成一个介于 0(包括)和 1(不包括)之间的随机双精度浮点数。

    double randomDouble = random.nextDouble();
    
  5. nextFloat(): 生成一个介于 0(包括)和 1(不包括)之间的随机单精度浮点数。

    float randomFloat = random.nextFloat();
    
  6. nextBoolean(): 生成一个随机的布尔值,truefalse

    boolean randomBoolean = random.nextBoolean();
    
  7. nextBytes(byte[] bytes): 将随机字节填充到指定的字节数组中。

    byte[] randomBytes = new byte[10];
    random.nextBytes(randomBytes);
    
  8. setSeed(long seed): 使用指定的种子值初始化随机数生成器。使用相同的种子可以确保每次运行程序时生成的随机数序列相同。

    long seed = System.currentTimeMillis();
    random.setSeed(seed);
    
  9. shuffle(int[] array): 使用默认随机源对指定数组中的元素进行随机排序。

    int[] array = {1, 2, 3, 4, 5};
    random.shuffle(array);
    
  10. shuffle(int[] array, int fromIndex, int toIndex): 使用默认随机源对指定数组中的元素进行随机排序,从 fromIndex(包括)到 toIndex(不包括)。

    int[] array = {1, 2, 3, 4, 5};
    random.shuffle(array, 1, 4); // 从索引 1 开始到索引 3(不包括)的元素进行随机排序
    

这些方法为开发人员提供了生成各种类型随机数的功能,以满足不同的需求。

推荐阅读:
  1. java中随机数生成方式有哪些
  2. java random类

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何在Java中使用Random类

下一篇:Java Random与Math.random有什么区别

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》