在java中产生随机数,在Java中生成唯一随机数

本文介绍了如何在Java中生成不重复的随机数。通过创建一个ArrayList,将1到100的数字依次添加并使用Collections.shuffle()打乱顺序,然后取出前n个元素,可以确保每次获取的随机数序列都是唯一的。这种方法避免了使用同一个Random实例导致的重复问题,因为Random实例如果使用相同的种子会产生相同的序列。
摘要由CSDN通过智能技术生成

I'm trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32 and not 82,12,53,12,32

I used this, but it generates same numbers in a sequence.

Random rand = new Random();

selected = rand.nextInt(100);

解决方案

Add each number in the range sequentially in a list structure.

Take the first 'n'.

Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.

import java.util.ArrayList;

import java.util.Collections;

public class UniqueRandomNumbers {

public static void main(String[] args) {

ArrayList list = new ArrayList();

for (int i=1; i<11; i++) {

list.add(new Integer(i));

}

Collections.shuffle(list);

for (int i=0; i<3; i++) {

System.out.println(list.get(i));

}

}

}

The first part of the fix with the original approach, as Mark Byers pointed out in an answer now deleted, is to use only a single Random instance.

That is what is causing the numbers to be identical. A Random instance is seeded by the current time in milliseconds. For a particular seed value, the 'random' instance will return the exact same sequence of pseudo random numbers.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值