可能重複:
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