才子佳人博客

我的故事我讲述

使用Java生成指定长度的随机字符串方法(附源码调试通过)
 
来源:xjh  编辑:xjh  2018-10-22
随机数在实际中使用很广泛,比如要随即生成一个固定长度的字符串、数字。或者随即生成一个不定长度的数字、或者进行一个模拟的随机选择等等。Java提供了最基本的工具,可以帮助开发者来实现这一切。

一、Java随机数的产生方式

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

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

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

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

二、java.util.Random类有两种方式构建方式:带种子和不带种子

1、不带种子:此种方式将会返回随机的数字,每次运行结果不一样。

2、带种子:无论程序运行多少次,返回结果都是一样的。

三、 Random description

public class Random
extends Object
implements Serializable
Random()
Creates a new random number generator.
Random(long seed)
Creates a new random number generator using a single long seed:

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

public int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generators sequence.

源码下载:Java生成指定长度的随机字符串源代码

参考:http://www.huomo.cn/developer/article-197ce.html


分类:编程开发| 查看评论
相关文章
文章点击排行
本年度文章点击排行
发表评论:
  • 昵称: *
  • 邮箱: *
  • 网址:
  • 评论:(最多100字)
  • 验证码: