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:
- Must be guaranteed to be unique, and this is generally based on time changes.
- 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