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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM