问题
Java's UUID class generates a random UUID. But this consists of alphabets and numbers. For some applications we need only numbers. Is there a way to generate random UUID that consists of only numbers in Java ?
UUID.randomUUID();
回答1:
If you dont want a random number, but an UUID with numbers only use:
String lUUID = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
in this case left padded to 40 zeros...
results for:
UUID : b55081fa-9cd1-48c2-95d4-efe2db322a54
in:
UUID : 0241008287272164729465721528295504357972
回答2:
Why don't just generate Random number and put it into format you want?
This won't give you uniqueness out of the box. (i.e. You will have to implement check on each generation and retry logic)
Where as other solutions which are taking UUID bits and converting them to number will be more granular in uniqueness. depending on your usecase you might still want to check uniqueness with this approach.
回答3:
Although the original poster of this question marked @Jigar Joshi's question as the best answer, I'd like to add that there is a rationale to use UUIDs rather than random numbers in certain cases. The difference is that UUIDs are (universally) unique (hence the name) while random numbers are not. It's just a question of probability whether you get the same number twice or even more often when generating random numbers, but this will never happen with UUIDs. Therefore, I'd consider @Chris Eibl's answer as the best one.
回答4:
For the record: UUIDs are in fact 128 bit numbers.
What you see as an alphanumeric string is the representation of that 128 bit number using hexadecimal digits (0..9A..F).
The real solution is to transform the string into it's correspondent 128 bit number. And to store that you'll need two Longs (Long has 64 bit).
回答5:
UUID uuid = UUID.randomUUID();
String numericUUID = Long.toString(uuid.getMostSignificantBits())
+ Long.toString(uuid.getLeastSignificantBits());
回答6:
Why using the UUID class if you dont need an UUID? It sounds more like you need just a random number which can be achieved by using the java.util.Random
class.
回答7:
Random
is not universally unique. If you want to use UUIDs
as opposed to the Random class as suggested by others, you could simply use a regex to strip out everything except numerics from the UUID. Try something like this,
String id = UUID.randomUUID().toString().replaceAll("[^0-9]", "");
回答8:
Call hashCode()
on the UUID to get a unique integer.
回答9:
String uuid = UUID.randomUUID().toString().replaceAll("-", ""); //strips '-'
来源:https://stackoverflow.com/questions/8092970/is-there-a-way-to-generate-a-random-uuid-which-consists-only-of-numbers