Java產生不重複的數的方法

來源:互聯網
上載者:User

標籤:res   bsp   random   sim   long   返回   str   new   lan   

在開發時要給某些表加上編號,而且編號是唯一的,自己用時間產生了下,覺得可能存在並發情況。所以在網上查了一下,就是隨機產生。方法如下:

//方法一(用目前時間精確到毫秒,截取任意幾位)

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

Java產生不重複的數的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.