生成随机字符串的2种方法,请多多指教,还能不能继续优化
// 方法一利用ASCII码:生成10个随机字符串,且长度不大于10,然后添加进List集合
public void testSort2() {
List<String> list = new ArrayList<>();
Random random = new Random();
int temp = 0;
for (int k = 0; k < 10; k++) {
int n;
do {
n = random.nextInt(11);
} while (n == 0);
String str = "";
for (int i = 0; i < n; i++) {
do {
temp = random.nextInt(123);
} while (temp < 48 || (temp > 57) && (temp < 65) || (temp > 90) && (temp < 97));
char ch = (char) temp;
str += ch;
}
list.add(str);
}
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序后:" + list);
// Collections.sort(list);
// for (String str : list) {
// System.out.print(str + " ");
// }
}
// 方法二利用StringBuilder类:生成10个随机字符串,且长度不大于10,然后添加进List集合
public void testSort3() {
List<String> list = new ArrayList<>();
Random random = new Random();
String strList="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for (int i = 0; i < 10; i++) {
StringBuilder str = new StringBuilder();
int n;
do {
n = random.nextInt(11);
} while (n == 0);
do {
for (int j = 0; j < n; j++) {
int temp = random.nextInt(62);
str.append(strList.charAt(temp));
}
} while (list.contains(str.toString()));
list.add(str.toString());
}
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序后:" + list);
}