可能重复:
Is there a way to generate a random UUID, which consists only of numbers?如何创建整数UUID在Java
我不希望有在UUID
唯一整数字符..怎么做,在java
?
可能重复:
Is there a way to generate a random UUID, which consists only of numbers?如何创建整数UUID在Java
我不希望有在UUID
唯一整数字符..怎么做,在java
?
如果你所需要的仅仅是一个随机数,用户Random
类并调用nextInt()
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
这将产生没有字符的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);
一旦你做到这一点,你不能把它的UUID了。 – 2012-06-06 20:52:40
@VladLazarenko:为什么不呢? – cha0site
UUID *通用*唯一,不仅仅是您的系统唯一。一个UUID必须有字母和数字。你只是在寻找一个对你的系统来说唯一的整数ID吗? – woz