栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在JAVA中生成UUID字符串的有效方法(不带破折号的UUID.randomUUID()。toString())

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在JAVA中生成UUID字符串的有效方法(不带破折号的UUID.randomUUID()。toString())

最终基于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));}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496502.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号