Java的UUID简单生成方法

简介: java的uuid简单生成

package com.example.utils;

import cn.hutool.core.lang.UUID;

import cn.hutool.core.util.IdUtil;

 

public class getCreateUuid {

 

   public static void main(String[] args) {

       System.out.println("得到8位的UUID-(码): " + getUUID_8());

       System.out.println("得到16位的UUID-(数字): " + getUUID_16());

       System.out.println("得到32位的UUID-(码): " + getUUID_32());

   }

 

   /*得到16位的UUID-(数字)*/

   public static String getUUID_16() {

       int machineId = 1;// 最大支持1-9个集群机器部署

 

       int hashCodeV = UUID.randomUUID().toString().hashCode();

       if (hashCodeV < 0) {// 有可能是负数

           hashCodeV = -hashCodeV;

       }

       String string = machineId + String.format("%015d", hashCodeV);

       return string;

   }

 

   /*得到32位的UUID-(码)*/

   public static String getUUID_32() {

       return UUID.randomUUID().toString().replace("-", "").toLowerCase();

   }

 

   public static final String[] CHARS = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",

           "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",

           "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",

           "U", "V", "W", "X", "Y", "Z" };

 

   /*得到8位的UUID-(码)*/

   public static String getUUID_8() {

       StringBuffer shortBuffer = new StringBuffer();

       String uuid = UUID.randomUUID().toString().replace("-", "");

       for (int i = 0; i < 8; i++) {

           String str = uuid.substring(i * 4, i * 4 + 4);

           int x = Integer.parseInt(str, 16);

           shortBuffer.append(CHARS[x % 0x3E]);

       }

       return shortBuffer.toString();

   }

}


运行结果:

得到8位的UUID-(码): 68yZXVVm

得到16位的UUID-(数字): 1000000966435108

得到32位的UUID-(码): 14690bc5598848a08a23a7335d9a0ab2

目录
相关文章
|
20天前
|
Java
Java中ReentrantLock中tryLock()方法加锁分析
Java中ReentrantLock中tryLock()方法加锁分析
13 0
|
10天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
46 3
|
1天前
|
Java
判断不为空和不为空串的方法java
判断不为空和不为空串的方法java
|
1天前
|
Java API
【亮剑】Java的List,如何删除重复的元素,教你三个方法搞定!
【4月更文挑战第30天】本文介绍了三种Java中删除List重复元素的方法:1) 使用HashSet,借助其不允许重复值的特性;2) 利用Java 8 Stream API的distinct()方法;3) 对自定义对象重写equals()和hashCode()。每种方法都附带了代码示例,帮助理解和应用。
|
2天前
|
IDE Java 开发工具
基于Java程序设计的实验教学方法优化与实践
基于Java程序设计的实验教学方法优化与实践
9 1
|
4天前
|
存储 Java 索引
【JAVA】HashMap的put()方法执行流程
【JAVA】HashMap的put()方法执行流程
|
4天前
|
存储 算法 Java
【JAVA】Java 中 Set集合常用方法
【JAVA】Java 中 Set集合常用方法
|
6天前
|
Java
Java 与垃圾回收有关的方法
Java 与垃圾回收有关的方法
|
7天前
|
Java
Java基础&方法
Java基础&方法
|
7天前
|
Java 编译器
Java 方法
4月更文挑战第19天