zoukankan      html  css  js  c++  java
  • 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。 }

  • 相关阅读:
    idea 编译内存溢出
    版本兼容问题 用于数据存储的持久化
    java8 函数接口
    akka 的集群访问方式
    Akka Cluster Sharding
    讨厌的adb占用
    安卓编译 签名包
    linux 系统的 cache 过大,解决方案
    kotlin 简单处理 回调参数 加?
    HTML CSS + DIV实现局部布局
  • 原文地址:https://www.cnblogs.com/w1217/p/6136967.html
Copyright © 2011-2022 走看看