可能重复:
Is there a way to generate a random UUID, which consists only of numbers?
我不想在UUID
只有整数中使用字符..如何在java
中执行此操作?
答案 0 :(得分:5)
getMostSigBits()
和getLeastSigBits()
获取长值。 byte[]
。 BigInteger
对象。 BigInteger
的toString()将是一个可能为负的UUID。您可以通过将-
符号替换为1,以及其他类似技术来解决该问题。我没有测试过这个,但是whatevs #gimmetehcodez
long hi = id.getMostSignificantBits();
long lo = id.getLeastSignificantBits();
byte[] bytes = ByteBuffer.allocate(16).putLong(hi).putLong(lo).array();
BigInteger big = new BigInteger(bytes);
String numericUuid = big.toString().replace('-','1'); // just in case
答案 1 :(得分:3)
您需要2 long
来存储UUID
。
UUID myuuid = UUID.randomUUID();
long highbits = myuuid.getMostSignificantBits();
long lowbits = myuuid.getLeastSignificantBits();
System.out.println("My UUID is: " + highbits + " " + lowbits);
答案 2 :(得分:1)
这将生成一个没有字符的v4 UUID,但它的独特性会明显降低。
final int[] pattern = { 8, 4, 4, 4, 12 };
final int[] versionBit = { 2, 0 }; /* 3rd group, first bit */
final int version = 4;
final int[] reservedBit = { 3, 0 }; /* 4rd group, first bit */
final int reserved = 8; /* 8, 9, A, or B */
Random rand = new Random();
String numericUuid = "";
for (int i = 0; i < pattern.length; i++) {
for (int j = 0; j < pattern[i]; j++) {
if (i == versionBit[0] && j == versionBit[1])
numericUuid += version;
else if (i == reservedBit[0] && j == reservedBit[1])
numericUuid += reserved;
else
numericUuid += rand.nextInt(10);
}
numericUuid += "-";
}
UUID uuid = UUID.fromString(numericUuid.substring(0, numericUuid.length() - 1));
System.out.println(uuid);
您还可以使用以下代码强制使用以下代码:
UUID uuid = UUID.randomUUID();
while (StringUtils.containsAny(uuid.toString(), new char[] { 'a', 'b', 'c', 'd', 'e', 'f' })) {
uuid = UUID.randomUUID();
}
System.out.println(uuid);
答案 3 :(得分:0)
如果你需要的只是一个随机数,用户Random
类并致电nextInt()