2012-06-06 89 views
1

可能重複:
Is there a way to generate a random UUID, which consists only of numbers?如何創建整數UUID在Java

我不希望有在UUID唯一整數字符..怎麼做,在java

+5

一旦你做到這一點,你不能把它的UUID了。 – 2012-06-06 20:52:40

+0

@VladLazarenko:爲什麼不呢? – cha0site

+1

UUID *通用*唯一,不僅僅是您的系統唯一。一個UUID必須有字母和數字。你只是在尋找一個對你的系統來說唯一的整數ID嗎? – woz

回答

2

您需要2 long s到存儲UUID

UUID myuuid = UUID.randomUUID(); 
long highbits = myuuid.getMostSignificantBits(); 
long lowbits = myuuid.getLeastSignificantBits(); 
System.out.println("My UUID is: " + highbits + " " + lowbits); 
+2

這可能會有'-'標誌。 – corsiKa

+0

@corsiKa:我意識到這一點。此代碼表示使用2個整數的UUID。 – cha0site

0

如果你所需要的僅僅是一個隨機數,用戶Random類並調用nextInt()

4
  • 使用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 
+0

您也可以通過在byte []'的正確位置添加一個0字節來解決這個負面問題。 – cha0site

+0

示例代碼會很好。 – eskatos

+8

你......你一定是在開玩笑吧。這實際上使用一步一步的說明完成調用什麼方法和一切。 – corsiKa

0

這將產生沒有字符的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);