1public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", 2 "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", 3 "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", 4 "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", 5 "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", 6 "W", "X", "Y", "Z" }; 7 8 9public static String generateShortUuid() { 10 StringBuffer shortBuffer = new StringBuffer(); 11 String uuid = UUID.randomUUID().toString().replace("-", ""); 12 for (int i = 0; i < 8; i++) { 13 String str = uuid.substring(i * 4, i * 4 + 4); 14 int x = Integer.parseInt(str, 16); 15 shortBuffer.append(chars[x % 0x3E]); 16 } 17 return shortBuffer.toString(); 18 19}
短8位UUID思想其实借鉴微博短域名的生成方式,但是其重复概率过高,而且每次生成4个,需要随即选取一个。
本算法利用62个可打印字符,通过随机生成32位UUID,由于UUID都为十六进制,所以将UUID分成8组,每4个为一组,然后通过模62操作,结果作为索引取出字符,
//方法二:
1public String genRandomNum(){ 2 int maxNum = 36; 3 int i; 4 int count = 0; 5 char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 6 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 7 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; 8 StringBuffer pwd = new StringBuffer(""); 9 Random r = new Random(); 10 while(count < 8){ 11 i = Math.abs(r.nextInt(maxNum)); 12 if (i >= 0 && i < str.length) { 13 pwd.append(str[i]); 14 count ++; 15 } 16 } 17 return pwd.toString(); 18 }