2012-06-06 39 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);