小wang同学的代码还是有小问题。随机字符的代码是无法取到小写字母z的。
因为业务要求随机字符包括大小写和数字,在代码中写到 int randomAscii = random.nextInt(122)
java中nextInt取的是[lower, upper),z的ascii是122,所以程序是取不到z字符的。
争哥的例子告诉我们尽量不要用魔数,不但可读性不好,有时我们自己都糊涂,边界容易搞错。
我试着重写了一下,一起讨论讨论!
https://github.com/gdhucoder/Algorithms4/blob/master/designpattern/u34/IdGenerator.java
public static final String BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final char[] CHAR_SET = BASE62.toCharArray();
public static String generate() {
// get host name
String hostName = null;
try {
hostName = InetAddress.getLocalHost().getHostName();
String[] tokens = hostName.split("\\.");
hostName = tokens[tokens.length - 1];
} catch (UnknownHostException e) {
hostName = "UNKNOWN";
}
// random chars
char[] randomChars = new char[8];
Random random = new Random();
for (int i = 0; i < randomChars.length; i++) {
int rndIdx = random.nextInt(CHAR_SET.length);
randomChars[i] = CHAR_SET[rndIdx];
}
// generate id
String id = String.format("%s-%d-%s", hostName,
System.currentTimeMillis(), new String(randomChars));
return id;
}
展开