JAVA中Random类的Random r=new Random()和Random r=new Random(seedValue)的区别

本文详细解析了 Java 中 Random 类的工作原理及其两种构造方法的区别。一种构造方法使用系统时间作为随机种子,每次运行程序生成不同的随机数序列;另一种则指定随机种子,确保每次运行程序时产生相同的随机数序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

区别在于:

 Random r=new Random() 每次运行程序时seedValue不一样,得到的随机数序列不一样,一般会这么用

Random r=new Random(seedValue):  每次运行程序得到的随机数序列都是一样的。例如第一次运行程序得到的随机数是 2, 4, 1, 5, 7。那么重启程序,再次得到的随机数还是2, 4, 1, 5, 7

原因:

Random产生的随机数实际上属于伪随机数,是按照一定算法计算出来的。构造方法如果没有传入随机种子的话,系统会默认采用系统时间作为随机种子。
以下为Random类的源码。


    /**
     * Creates a new random number generator. This constructor sets
     * the seed of the random number generator to a value very likely
     * to be distinct from any other invocation of this constructor.
     */
    public Random() { this(++seedUniquifier + System.nanoTime()); }
    private static volatile long seedUniquifier = 8682522807148012L;

    /**
     * Creates a new random number generator using a single {@code long} seed.
     * The seed is the initial value of the internal state of the pseudorandom
     * number generator which is maintained by method {@link #next}.
     *
     * <p>The invocation {@code new Random(seed)} is equivalent to:
     *  <pre> {@code
     * Random rnd = new Random();
     * rnd.setSeed(seed);}</pre>
     *
     * @param seed the initial seed
     * @see   #setSeed(long)
     */
    public Random(long seed) {
        this.seed = new AtomicLong(0L);
        setSeed(seed);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值