转自:https://blog.csdn.net/YTTmiao/article/details/78187448

随机数在实际中使用很广泛,比如要随即生成一个固定长度的字符串、数字。或者随即生成一个不定长度的数字、或者进行一个模拟的随机选择等等。Java提供了最基本的工具,可以帮助开发者来实现这一切。

    一、Java随机数的产生方式

在Java中,随机数的概念从广义上将,有三种。

1、通过System.currentTimeMillis()来获取一个当前时间毫秒数的long型数字。

2、通过Math.random()返回一个0到1之间的double值。

3、通过Random类来产生一个随机数,这个是专业的Random工具类,功能强大。

    二、Random类API说明

1、Java API说明

Random类的实例用于生成伪随机数流。此类使用 48 位的种子,使用线性同余公式对其进行修改(请参阅 Donald Knuth 的《The Art of Computer Programming, Volume 2》,第 3.2.1 节)。

如果用相同的种子创建两个 Random 实例,则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。为了保证属性的实现,为类 Random 指定了特定的算法。

很多应用程序会发现 Math 类中的 random 方法更易于使用。

2、方法摘要

  1. Random()
  2. 创建一个新的随机数生成器。
  3. Random(long seed)
  4. 使用单个 long 种子创建一个新随机数生成器: public Random(long seed) { setSeed(seed); } next 方法使用它来保存随机数生成器的状态。
  5. protected  int next(int bits)
  6. 生成下一个伪随机数。
  7. boolean nextBoolean()
  8. 返回下一个伪随机数,它是从此随机数生成器的序列中取出的、均匀分布的 boolean 值。
  9. void nextBytes(byte[] bytes)
  10. 生成随机字节并将其置于用户提供的字节数组中。
  11. double nextDouble()
  12. 返回下一个伪随机数,它是从此随机数生成器的序列中取出的、在 0.0 和 1.0之间均匀分布的 double 值。
  13. float nextFloat()
  14. 返回下一个伪随机数,它是从此随机数生成器的序列中取出的、在 0.0 和 1.0 之间均匀分布的 float 值。
  15. double nextGaussian()
  16. 返回下一个伪随机数,它是从此随机数生成器的序列中取出的、呈高斯(“正常地”)分布的 double 值,其平均值是 0.0,标准偏差是 1.0。
  17. int nextInt()
  18. 返回下一个伪随机数,它是此随机数生成器的序列中均匀分布的 int 值。
  19. int nextInt(int n)
  20. 返回一个伪随机数,它是从此随机数生成器的序列中取出的、在 0(包括)和指定值(不包括)之间均匀分布的 int值。
  21. long nextLong()
  22. 返回下一个伪随机数,它是从此随机数生成器的序列中取出的、均匀分布的 long 值。
  23. void setSeed(long seed)
  24. 使用单个 long 种子设置此随机数生成器的种子。

三、Random类使用说明

1、带种子与不带种子的区别Random类使用的根本是策略分带种子和不带种子的Random的实例。

通俗说,两者的区别是:带种子的,每次运行生成的结果都是一样的。

不带种子的,每次运行生成的都是随机的,没有规律可言。

2、创建不带种子的Random对象

Random random = new Random();

3、创建不带种子的Random对象有两种方法:

1) Random random = new Random(555L);

2) Random random = new Random();random.setSeed(555L);

    四、测试

通过一个例子说明上面的用法

  1. import java.util.Random;
  2. public class TestRandomNum {
  3. public static void main(String[] args) {
  4. randomTest();
  5. testNoSeed();
  6. testSeed1();
  7. testSeed2();
  8. }
  9. public static void randomTest() {
  10. System.out.println("--------------test()--------------");
  11. //返回以毫秒为单位的当前时间。
  12. long r1 = System.currentTimeMillis();
  13. //返回带正号的 double 值,大于或等于 0.0,小于 1.0。
  14. double r2 = Math.random();
  15. //通过Random类来获取下一个随机的整数
  16. int r3 = new Random().nextInt();
  17. System.out.println("r1 = " + r1);
  18. System.out.println("r3 = " + r2);
  19. System.out.println("r2 = " + r3);
  20. }
  21. public static void testNoSeed() {
  22. System.out.println("--------------testNoSeed()--------------");
  23. //创建不带种子的测试Random对象
  24. Random random = new Random();
  25. for (int i = 0; i < 3; i++) {
  26. System.out.println(random.nextInt());
  27. }
  28. }
  29. public static void testSeed1() {
  30. System.out.println("--------------testSeed1()--------------");
  31. //创建带种子的测试Random对象
  32. Random random = new Random(555L);
  33. for (int i = 0; i < 3; i++) {
  34. System.out.println(random.nextInt());
  35. }
  36. }
  37. public static void testSeed2() {
  38. System.out.println("--------------testSeed2()--------------");
  39. //创建带种子的测试Random对象
  40. Random random = new Random();
  41. random.setSeed(555L);
  42. for (int i = 0; i < 3; i++) {
  43. System.out.println(random.nextInt());
  44. }
  45. }
  46. }

运行结果:

  1. --------------test()--------------
  2. r1 = 1227108626582
  3. r3 = 0.5324887850155043
  4. r2 = -368083737
  5. --------------testNoSeed()--------------
  6. 809503475
  7. 1585541532
  8. -645134204
  9. --------------testSeed1()--------------
  10. -1367481220
  11. 292886146
  12. -1462441651
  13. --------------testSeed2()--------------
  14. -1367481220
  15. 292886146
  16. -1462441651
  17. Process finished with exit code 0

通过testSeed1()与testSeed2()方法的结果可以看到,两个打印结果相同,因为他们种子相同,再运行一次,结果还是一样的,这就是带种子随机数的特性。

而不带种子的,每次运行结果都是随机的。

五、综合应用

下面通过最近写的一个随机数工具类来展示用法:

  1. import java.util.Random;
  2. /**
  3. * 随机数、随即字符串工具
  4. */
  5. public class RandomUtils {
  6. public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  7. public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  8. public static final String numberChar = "0123456789";
  9. /**
  10. * 返回一个定长的随机字符串(只包含大小写字母、数字)
  11. *
  12. * @param length 随机字符串长度
  13. * @return 随机字符串
  14. */
  15. public static String generateString(int length) {
  16. StringBuffer sb = new StringBuffer();
  17. Random random = new Random();
  18. for (int i = 0; i < length; i++) {
  19. sb.append(allChar.charAt(random.nextInt(allChar.length())));
  20. }
  21. return sb.toString();
  22. }
  23. /**
  24. * 返回一个定长的随机纯字母字符串(只包含大小写字母)
  25. *
  26. * @param length 随机字符串长度
  27. * @return 随机字符串
  28. */
  29. public static String generateMixString(int length) {
  30. StringBuffer sb = new StringBuffer();
  31. Random random = new Random();
  32. for (int i = 0; i < length; i++) {
  33. sb.append(allChar.charAt(random.nextInt(letterChar.length())));
  34. }
  35. return sb.toString();
  36. }
  37. /**
  38. * 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
  39. *
  40. * @param length 随机字符串长度
  41. * @return 随机字符串
  42. */
  43. public static String generateLowerString(int length) {
  44. return generateMixString(length).toLowerCase();
  45. }
  46. /**
  47. * 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
  48. *
  49. * @param length 随机字符串长度
  50. * @return 随机字符串
  51. */
  52. public static String generateUpperString(int length) {
  53. return generateMixString(length).toUpperCase();
  54. }
  55. /**
  56. * 生成一个定长的纯0字符串
  57. *
  58. * @param length 字符串长度
  59. * @return 纯0字符串
  60. */
  61. public static String generateZeroString(int length) {
  62. StringBuffer sb = new StringBuffer();
  63. for (int i = 0; i < length; i++) {
  64. sb.append('0');
  65. }
  66. return sb.toString();
  67. }
  68. /**
  69. * 根据数字生成一个定长的字符串,长度不够前面补0
  70. *
  71. * @param num             数字
  72. * @param fixdlenth 字符串长度
  73. * @return 定长的字符串
  74. */
  75. public static String toFixdLengthString(long num, int fixdlenth) {
  76. StringBuffer sb = new StringBuffer();
  77. String strNum = String.valueOf(num);
  78. if (fixdlenth - strNum.length() >= 0) {
  79. sb.append(generateZeroString(fixdlenth - strNum.length()));
  80. } else {
  81. throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");
  82. }
  83. sb.append(strNum);
  84. return sb.toString();
  85. }
  86. /**
  87. * 根据数字生成一个定长的字符串,长度不够前面补0
  88. *
  89. * @param num             数字
  90. * @param fixdlenth 字符串长度
  91. * @return 定长的字符串
  92. */
  93. public static String toFixdLengthString(int num, int fixdlenth) {
  94. StringBuffer sb = new StringBuffer();
  95. String strNum = String.valueOf(num);
  96. if (fixdlenth - strNum.length() >= 0) {
  97. sb.append(generateZeroString(fixdlenth - strNum.length()));
  98. } else {
  99. throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");
  100. }
  101. sb.append(strNum);
  102. return sb.toString();
  103. }
  104. public static void main(String[] args) {
  105. System.out.println(generateString(15));
  106. System.out.println(generateMixString(15));
  107. System.out.println(generateLowerString(15));
  108. System.out.println(generateUpperString(15));
  109. System.out.println(generateZeroString(15));
  110. System.out.println(toFixdLengthString(123, 15));
  111. System.out.println(toFixdLengthString(123L, 15));
  112. }
  113. }
  1. import java.util.Random;
  2. /**
  3. * 随机数、随即字符串工具
  4. */
  5. public class RandomUtils {
  6. public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  7. public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  8. public static final String numberChar = "0123456789";
  9. /**
  10. * 返回一个定长的随机字符串(只包含大小写字母、数字)
  11. *
  12. * @param length 随机字符串长度
  13. * @return 随机字符串
  14. */
  15. public static String generateString(int length) {
  16. StringBuffer sb = new StringBuffer();
  17. Random random = new Random();
  18. for (int i = 0; i < length; i++) {
  19. sb.append(allChar.charAt(random.nextInt(allChar.length())));
  20. }
  21. return sb.toString();
  22. }
  23. /**
  24. * 返回一个定长的随机纯字母字符串(只包含大小写字母)
  25. *
  26. * @param length 随机字符串长度
  27. * @return 随机字符串
  28. */
  29. public static String generateMixString(int length) {
  30. StringBuffer sb = new StringBuffer();
  31. Random random = new Random();
  32. for (int i = 0; i < length; i++) {
  33. sb.append(allChar.charAt(random.nextInt(letterChar.length())));
  34. }
  35. return sb.toString();
  36. }
  37. /**
  38. * 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
  39. *
  40. * @param length 随机字符串长度
  41. * @return 随机字符串
  42. */
  43. public static String generateLowerString(int length) {
  44. return generateMixString(length).toLowerCase();
  45. }
  46. /**
  47. * 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
  48. *
  49. * @param length 随机字符串长度
  50. * @return 随机字符串
  51. */
  52. public static String generateUpperString(int length) {
  53. return generateMixString(length).toUpperCase();
  54. }
  55. /**
  56. * 生成一个定长的纯0字符串
  57. *
  58. * @param length 字符串长度
  59. * @return 纯0字符串
  60. */
  61. public static String generateZeroString(int length) {
  62. StringBuffer sb = new StringBuffer();
  63. for (int i = 0; i < length; i++) {
  64. sb.append('0');
  65. }
  66. return sb.toString();
  67. }
  68. /**
  69. * 根据数字生成一个定长的字符串,长度不够前面补0
  70. *
  71. * @param num             数字
  72. * @param fixdlenth 字符串长度
  73. * @return 定长的字符串
  74. */
  75. public static String toFixdLengthString(long num, int fixdlenth) {
  76. StringBuffer sb = new StringBuffer();
  77. String strNum = String.valueOf(num);
  78. if (fixdlenth - strNum.length() >= 0) {
  79. sb.append(generateZeroString(fixdlenth - strNum.length()));
  80. } else {
  81. throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");
  82. }
  83. sb.append(strNum);
  84. return sb.toString();
  85. }
  86. /**
  87. * 根据数字生成一个定长的字符串,长度不够前面补0
  88. *
  89. * @param num             数字
  90. * @param fixdlenth 字符串长度
  91. * @return 定长的字符串
  92. */
  93. public static String toFixdLengthString(int num, int fixdlenth) {
  94. StringBuffer sb = new StringBuffer();
  95. String strNum = String.valueOf(num);
  96. if (fixdlenth - strNum.length() >= 0) {
  97. sb.append(generateZeroString(fixdlenth - strNum.length()));
  98. } else {
  99. throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");
  100. }
  101. sb.append(strNum);
  102. return sb.toString();
  103. }
  104. public static void main(String[] args) {
  105. System.out.println(generateString(15));
  106. System.out.println(generateMixString(15));
  107. System.out.println(generateLowerString(15));
  108. System.out.println(generateUpperString(15));
  109. System.out.println(generateZeroString(15));
  110. System.out.println(toFixdLengthString(123, 15));
  111. System.out.println(toFixdLengthString(123L, 15));
  112. }
  113. }

运行结果:

    1. vWMBPiNbzfGCpHG
    2. 23hyraHdJkKPwMv
    3. tigowetbwkm1nde
    4. BPZ1KNEJPHB115N
    5. 000000000000000
    6. 000000000000123
    7. 000000000000123
    8. Process finished with exit code 0

最新文章

  1. Android Studio的下载和安装教程(从ADT到AS)
  2. 一般处理程序上传文件(html表单上传、aspx页面上传)
  3. CSS3–1.css3 新增选择器
  4. java Joda-Time 对日期、时间操作
  5. Linux第八次学习笔记
  6. sql server还原数据库文件(.bak)常见问题解决办法笔记
  7. JavaScript如何获得昨天明天等日期
  8. ionic goto other page or alert
  9. js各种宽高(2)
  10. 3)Java容器
  11. 20160122.CCPP详解体系(0001天)
  12. Adobe Acrobat XI Pro 两种破解方式 Keygen秘钥 license替换 亲测有效
  13. LVS的十种调度算法
  14. HTTPS和HTTP有什么区别?如何将HTTP转化成HTTPS
  15. 常用Markdown公式整理 &amp;&amp; 页内跳转注意 &amp;&amp; Markdown preview
  16. IDEA使用教程
  17. JHipster生成微服务架构的应用栈(三)- 业务微服务示例
  18. queue之#单向消息队列
  19. 学习使用JUnit4进行单元测试
  20. Synchronized常用用法

热门文章

  1. NYOJ_77 开灯问题
  2. uvalive 6669 hidden tree(好壮压dp)
  3. mysql简单优化思路
  4. Linux软件万花筒
  5. 分享一个正则 选择html中所有的单标签
  6. 电脑无法上网,DHCP客户端不能正确获取IP地址
  7. 使用js实现简单放大镜的效果
  8. 【Henu ACM Round #13 A】 Hulk
  9. xgboost参数调优的几个地方
  10. [Python] Read and Parse Files in Python