- 代码展示
import java.util.Random;
public class RandomStringUtils {
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
int number = random.nextInt(52);// [0,51)
sb.append(str.charAt(number));
}
return sb.toString();
}
public static String getRandomString2(int length) {
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
int number = random.nextInt(2);
long result = 0;
switch (number) {
case 0:
/* A-Z 的 ASCII 码值[65,90] */
result = Math.round(Math.random() * 25 + 65);
sb.append(String.valueOf((char) result));
break;
case 1:
/* a-z 的 ASCII 码值[97,122] */
result = Math.round(Math.random() * 25 + 97);
sb.append(String.valueOf((char) result));
break;
}
}
return sb.toString();
}
}
- 性能测试
public static void main(String[] args) {
String inviteCode = "";
long l1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
inviteCode = getRandomString(6);
}
long l2 = System.currentTimeMillis();
System.out.println("方法一生成字符串“" + inviteCode + "”花费" + (l2 - l1) + "毫秒");
l1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
inviteCode = getRandomString2(6);
}
l2 = System.currentTimeMillis();
System.out.println("方法二生成字符串“" + inviteCode + "”花费" + (l2 - l1) + "毫秒");
}
为了直观,循环执行10000000次。
方法一生成字符串“XDNYfX”花费1275毫秒;
方法二生成字符串“JVQFpr”花费2906毫秒;