HashSet排序假象

        在实际开发中我们会遇到这样的需求,生成1-10的随机乱序不重复数字。首先想到的就是Random生成随机数,然后将这些随机数放入set中,利用set的特性排除相同数据。最后输出set里面的数字。但是实际使用的时候会有文中的问题。

        我们在使用HashSet的时候都知道,Set的特性是元素唯一,并且乱序存储。但是在实际时候的时候。会有下面的情况发生:

源码如下:
        publicvoid test1() throws InterruptedException{
            long randomSeed= System.currentTimeMillis() ;
           Random random = new Random(45) ;
           Set randomSet = new HashSet() ;
           System.out.println("开始放入:");
           for(int i = 0 ; i < 100 ; i++){
               Integer in = random.nextInt(10) ;
               System.out.print(in+" , ");
               randomSet.add(in) ;
               TimeUnit.MILLISECONDS.sleep(2);
           } 
           System.out.println() ;
           System.out.println("结果:");
           System.out.println(randomSet.toString()) ;
            }

        }


以上代码的输出:

开始放入:
9 , 1 , 1 , 0 , 7 , 1 , 1 , 3 , 4 , 3 , 0 , 9 , 0 , 8 , 0 , 6 , 4 , 5 , 0 , 7 ,2 , 1 , 4 , 4 , 8 , 9 , 7 , 0 , 9 , 1 , 2 , 3 , 1 , 2 , 4 , 3 , 9 , 0 , 7 , 0 ,1 , 1 , 2 , 4 , 3 , 1 , 7 , 3 , 2 , 1 , 9 , 0 , 2 , 2 , 2 , 3 , 6 , 5 , 8 , 3 ,1 , 0 , 3 , 4 , 0 , 1 , 3 , 2 , 4 , 8 , 7 , 1 , 5 , 1 , 4 , 1 , 7 , 9 , 3 , 4 ,5 , 3 , 7 , 1 , 9 , 0 , 0 , 3 , 4 , 7 , 4 , 1 , 8 , 7 , 4 , 3 , 8 , 9 , 2 , 2,
结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

这里HashSet.toString()给出的输出结果貌似进行了排序,如果将toString的输出修改成for的遍历看,如下:

    for(Integer ele : randomSet){
        System.out.print(ele+" , ") ;
&
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值