• Java生成不重复的数的方法


    在开发时要给某些表加上编号,而且编号是唯一的,自己用时间生成了下,觉得可能存在并发情况。所以在网上查了一下,就是随机生成。方法如下:

    //方法一(用当前时间精确到毫秒,截取任意几位)

           Date date = new Date();

     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSS");

           String  formDate =sdf.format(date);

            System.out.println(formDate);

            String no = formDate.substring(10);

            System.out.println(no);

           

            //方法二(随机生成)

            int[] array ={0,1,2,3,4,5,6,7,8,9};

            Random rand = new Random();

            for (int i = 10; i > 1; i--) {

                int index =rand.nextInt(i);

                int tmp =array[index];

                array[index] = array[i - 1];

                array[i - 1] = tmp;

            }

            int result = 0;

            for(int i = 0; i < 6; i++)

                result = result * 10 + array[i];

            System.out.println(result);

     

             //方法三:利用时间戳得到8位不重复的随机数

            long nowDate = new Date().getTime();

            String sid = Integer.toHexString((int)nowDate);

            System.out.println(sid);

            /*其中:java.lang.Integer.toHexString() 方法返回为无符号整数基数为16的整

            */参数的字符串表示形式。以下字符作为十六进制数字:0123456789ABCDEF。 }

  • 相关阅读:
    基于TFTP协议的远程升级设计
    BZOJ 刷题记录 PART 6
    解决org.hibernate.LazyInitializationException: could not initialize proxy
    在不同版本号hdfs集群之间转移数据
    从零開始制作H5应用(4)——V4.0,增加文字并给文字加特效
    不再安全的 OSSpinLock
    @synchronized 再考察
    ReactiveCocoa
    怎样界定问题
    问题是什么
  • 原文地址:https://www.cnblogs.com/w1217/p/6136967.html
Copyright © 2020-2023  润新知