java之生成随机数的方式1:Random.nextInt()

本文详细介绍了Java中使用java.util.Random类的nextInt()方法生成随机数的方法,包括无参和有参构造器的使用,以及nextInt()和nextInt(int)两个方法的区别。通过实例代码展示了不同构造方式和方法调用如何影响随机数生成,强调了random.nextInt(10)是决定生成[0, 9]范围内随机数的关键。" 126214486,15028472,HTML5个人网页设计与实现:从零开始制作校园网站,"['HTML静态网页作业', 'web前端开发技术', '网页规划与设计', 'HTML5期末考核大作业', '个人网页设计与实现']

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

java中生成随机数的方式之1:

利用 java.util.Random 工具类可以生成随机数,以jdk1.8为例

 

1、Random对象的创建

     我们先来看下Random的构造方法

// 无参构造
public Random(){}

// 带参构造
public Random(long seed){}

  我们来看一下它的相关源码:

    /** 
     * 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());
    }

    /**
     * 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) {
        if (getClass() == Random.class)
            this.seed = new AtomicLong(initialScramble(seed));
        else {
            // subclass might have overriden setSeed
            this.seed = new AtomicLong();
            setSeed(seed);
        }
    }

 从源码中我们可以获取的信息有:

对于无参构造方法,

Random() 在创建对象时,会生成一个随机数作为种子,利用这个种子生成新的随机数。而这个随机数是当前系统时间的纳秒值和另外一个长整型毫秒值的异或运算的结果【this(seedUniquifier() ^ System.nanoTime())

对于有参构造方法,

根据方法上的注释,我们发现 

方式1:

Random rd1 = new Random(10);

等价于以下语法

方式2:

Random rd2 = new Random();

rd.nextInt(10);

但是,实际测试中,并没有这么简单,请参照第3标题下的内容。

2、Random对象的生成随机数的相关方法

Random类中,生成随机整数的相关方法有:

    /**
     * ...
     * @return the next pseudorandom, uniformly distributed {@code int}
     *         value from this random number generator's sequence
     */
    public int nextInt() {
        return next(32);
    }

    /**
     * ...
     * @param bound the upper bound (exclusive).  Must be positive.
     * @return the next pseudorandom, uniformly distributed {@code int}
     *         value between zero (inclusive) and {@code bound} (exclusive)
     *         from this random number generator's sequence
     * @throws IllegalArgumentException if bound is not positive
     * @since 1.2
     */
    public int nextInt(int bound) {
        if (bound <= 0)
            throw new IllegalArgumentException(BadBound);

        int r = next(31);
        int m = bound - 1;
        if ((bound & m) == 0)  // i.e., bound is a power of 2
            r = (int)((bound * (long)r) >> 31);
        else {
            for (int u = r;
                 u - (r = u % bound) + m < 0;
                 u = next(31))
                ;
        }
        return r;
    }

nextInt() 和 nextInt(int) 这两个方法都可以用来生成随机数。

但是它们两个方法的区别在于

   假设 Random ra = new Random();

   ra.nextInt()     会生成一个任意的 随机整数(包括正数和负数)

   ra.nextInt(int)  会生成一个 [0,9] 之间的任意一个整数

测试代码如下:

public class TestRandomConstructor {
	public static void main(String[] args) {
		System.out.println("========================= nextInt(10) ================");
		Random rd1 = new Random();
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt(10));
		}
		System.out.println("========================= nextInt() ================");
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt());
		}
	}
}

测试结果:

========================= nextInt(10) ================
7
7
8
1
8
2
7
6
1
0
...
========================= nextInt() ================
439364996
1142968751
-1245259674
-896549010
-1870260620
1931734780
1153394322
-1781928093
....

3、其他知识点

假设   Random ra = new Random(10);

测试代码:

public class TestRandomConstructor {
	public static void main(String[] args) {
		System.out.println("========================= nextInt(10) ================");
		Random rd1 = new Random(10);
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt(10));
		}
		System.out.println("========================= nextInt() ================");
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt());
		}
	}
}

测试结果:

========================= nextInt(10) ================
3
0
3
0
6
6
7
8
1
4
3
8
......
========================= nextInt() ================
35545786
-347474078
1892459190
498897016
134578271
-1339421797
-331953347
772426541
1684007666
......

    所以,最终我们可以得出结论,决定最后生成的随机数的是 random.nextInt(10)

    而不是 Random ra = new Random(10); 

 

此文希望可以帮助到大家。如有错误,请指教。                                                           

如果大家还有其他的情况或者好的解决方法,也望指教,感谢阅读。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值