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

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

       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。 }

posted on 2016-12-06 11:37  那些花  阅读(14578)  评论(0编辑  收藏  举报