在JAVA中生成UUID字符串的有效方法(UUID.randomUUID()。toString(),不带破折号) [英] Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

查看:2982
本文介绍了在JAVA中生成UUID字符串的有效方法(UUID.randomUUID()。toString(),不带破折号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个有效的实用程序来生成唯一的字节序列。 UUID是一个很好的候选者,但是 UUID.randomUUID()。toString()会产生类似 44e128a5-ac7a-4c9a-be4c-224b6bf81b20 只要您不需要通过HTTP传输它就是好的,在这种情况下需要删除破折号。

I would like an efficient utility to generate unique sequences of bytes. UUID is a good candidate but UUID.randomUUID().toString() generates stuff like 44e128a5-ac7a-4c9a-be4c-224b6bf81b20 which is good as long as you don't need to transmit it over HTTP, in which case the dashes need to be removed.

我正在寻找生成随机字符串的有效方法,仅使用字母数字字符(无破折号或任何其他特殊符号)。

I'm looking for an efficient way to generate a random strings, only from alphanumeric characters (no dashes or any other special symbols).

推荐答案

结束根据UUID.java实现编写自己的东西。请注意,我没有生成UUID ,而只是一个随机的32字节十六进制字符串,以我能想到的最有效的方式。

Ended up writing something of my own based on UUID.java implementation. Note that I'm not generating a UUID, instead just a random 32 bytes hex string in the most efficient way I could think of.

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());
    }       
}



用法



Usage

RandomUtil.unique()



测试



我测试过的一些输入以确保它正常工作:

Tests

Some of the inputs I've tested to make sure it's working:

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));
}

这篇关于在JAVA中生成UUID字符串的有效方法(UUID.randomUUID()。toString(),不带破折号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆