Generation of unique numbers in Java

Source: Internet
Author: User

The generation of unique numbers is simple and is basically generated on a time-based basis. There are already java.util.UUID classes in the JDK that can generate a unique random number. If you want to generate a unique number for a specific format, you need to generate a unique number yourself. There are two factors that must be considered when generating a unique number:

    1. Must be guaranteed to be unique, and this is generally based on time changes.
    2. Efficient, of course, the more efficient the better.

Sometimes we want to include specific content in the generated unique number, such as the current time, such as 20110609132641, as a prefix. The following fragments are available for reference:

1 Importjava.util.Date;2 3 4  Public classGenerateuuid {5     Private StaticDate Date =NewDate (); 6 //private static StringBuilder buf = new StringBuilder (); 7     Private Static intSeq = 0; 8     Private Static Final intROTATION = 99999; 9      Public Static synchronized LongNext () {Ten       if(seq > ROTATION) seq = 0;  One //buf.delete (0, Buf.length ());  A Date.settime (System.currenttimemillis ());  -String str = String.Format ("%1$ty%1$tm%1$td%1$tk%1$tm%1$ts%2$05d", date, seq++);  -       returnLong.parselong (str);  the   }   -      Public Static voidMain (string[] args) { -          for(inti=0;i<100;i++){   - System.out.println (Next ());  +         }   -   }   +}

Generation of unique numbers in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.