简体   繁体   中英

Unique Random Number Creation in java

I am creating 10 digit random unique numbers in java am able to create but Numbers are repeating after some numbers, i want to create unique numbers which should not be repeated even server restart also, i want solution like UUID.randomUUID() for 10 digit number.

Am using below Code

(long) Math.floor(Math.random() * 9_000_000_000L) + 1_000_000_000L

This code is not producing unique 10 digit numbers.

Given that there are a finite number (10^10) 10 digit numbers, you cannot do this indefinitely, as eventually you will run out of new unique numbers.

The Apache Commons Lang library has a method RandomStringUtils.randomNumeric(int count) which, as the name suggests, produces a String of a given length containing random digits, which can then be mapped to a long using Long.parseLong() .

Using this, you can generate random values. You must then store these values (probably in some kind of database, depending on your deployment situation), and verify that any new values have not been used before.

Note that this method will not check for leading zeroes, so if that is important to you, you must do that as well.

Also note, the longer you go without repeating values, the more predictable (and therefore less random) the values become. If you are using this for cryptographic/security conscious purposes, you must use a cryptographically secure random number generator (look into SecureRandom in the JDK).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM