I need make id for student tickets that consists of 6-digit number. For example, 000004 or 123456 and it must be unique so dont repeat. I want to make it using UUID, bit i don't understand how to make confines.
-
2Generate all million numbers in a list. If you want them in a random order, shuffle. Then take the first N items from the list. – Andy Turner Sep 29 '18 at 21:01
-
3Why do you need UUID, which by the way is larger than 6 digits, you can generate them sequentially one after the other starting in 100000. – Juan Sep 29 '18 at 21:12
-
5See this question, UUID is not suitable for what you want. The uniqueness of the uuid is in part based on its length. https://stackoverflow.com/questions/292965/what-is-a-uuid – Juan Sep 29 '18 at 21:16
1 Answers
Random number, 1 to 999,999
See the Question, How to generate random integers within a specific range in Java?.
int min = 1 ;
int max = 999_999 ;
int randomNum = ThreadLocalRandom.current().nextInt( min , max + 1 );
With such a small range of a million, you will frequently have collisions (duplicates).
To avoid duplicates, you must collect all used numbers, and search that collection each time you attempt generating an identifier. You must do so in a thread-safe manner.
Not recommended for your purpose.
Not practical
A random six-digit number is not sufficiently large to be used as an identifier in any important context. That is one reason why numbers for employee badges and similar use-cases are done as a sequence (000001, 000002, etc.).
UUID
If you want a truly universally unique identifier, use a Universally Unique Identifier.
As a 128-bit value, you have an astronomically larger range of values than your million. The Version 1 type of UUID eliminates any practical possibility of collisions. That is why it was invented and standardized.
For a small number of cases, such as your million students, even the mostly-random Version 4 is good enough. This is the version generated by UUID.randomUUID
.

- 303,325
- 100
- 852
- 1,154