我想要一个高效的实用程序来生成唯一的字节序列。UUID是一个很好的候选人,但是会UUID.randomUUID().toString()
生成类似的东西44e128a5-ac7a-4c9a-be4c-224b6bf81b20
,但是我更喜欢无破折号的字符串。
我正在寻找一种仅从字母数字字符(无破折号或任何其他特殊符号)生成随机字符串的有效方法。
最终基于UUID.java实现编写了自己的东西。请注意,我并不是在生成UUID,而是以我能想到的最有效的方式生成一个随机的32字节十六进制字符串。
import java.security.SecureRandom;
import java.util.UUID;
public class RandomUtil {
// Maxim: Copied from UUID implementation :)
private static volatile SecureRandom numberGenerator = null;
private static final long MSB = 0x8000000000000000L;
public static String unique() {
SecureRandom ng = numberGenerator;
if (ng == null) {
numberGenerator = ng = new SecureRandom();
}
return Long.toHexString(MSB | ng.nextLong()) + Long.toHexString(MSB | ng.nextLong());
}
}
RandomUtil.unique()
我已经测试过一些输入,以确保它可以正常工作:
public static void main(String[] args) {
System.out.println(UUID.randomUUID().toString());
System.out.println(RandomUtil.unique());
System.out.println();
System.out.println(Long.toHexString(0x8000000000000000L |21));
System.out.println(Long.toBinaryString(0x8000000000000000L |21));
System.out.println(Long.toHexString(Long.MAX_VALUE + 1));
}
不知道为什么还要增加这个价格,在这里编写的所有选项中,这是最有效的方法,它生成的UUID不带“-”。字符串替换不是更好,然后从long转换为string。两者都为O(n)是正确的,但是在规模上,每分钟您生成数百万个uuid的值就变得有意义。