【发布时间】:2013-12-03 20:31:00
【问题描述】:
我正在尝试使 java UUID 更短,同时保留与 UUID 相同的唯一性。 我写了以下代码:
public static void main(String[] args) {
UUID uid=UUID.randomUUID();
String shortId=to62System(uid.getMostSignificantBits())+
to62System(uid.getLeastSignificantBits());
System.out.println(shortId);
}
static char[] DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
static int RADIX = DIGITS.length;
public static String to62System(long value) {
if (value == 0) {
return "0";
} else {
char[] buf = new char[11];
int charPos = 10;
long i = value;
while (i != 0) {
buf[charPos--] = DIGITS[Math.abs((int) (i % RADIX))];
i /= RADIX;
}
return new String(buf, charPos + 1, (10 - charPos));
}
}
我做得对还是我忽略了一些重要的事情?
【问题讨论】:
-
只是好奇,你为什么要这样做?
-
你不能:blogs.msdn.com/b/oldnewthing/archive/2008/06/27/8659071.aspx(编辑:我实际上不确定 randomUUID() 是否使用相同的算法,但很有可能它仍然不是一个好主意)。
-
唯一的空间是什么?这限制了 ID 的大小。
-
@Zavior 我需要尽可能短的 worldwide 唯一 ID,可在 URL 中使用。例如,它必须很短才能在推文中使用。是的,有一些网址缩短服务,但我不想使用它。
-
@WPrecht 全球独一无二。