手记

应用 Collections.sort() 实现 List 排序 -随机生成字符串练习

// 插入十个随机字符串,每条字符串的长度为10以内的随机整数,
//每条字符串的每个字符都为随机生成的字符,字符可以重复
//每条随机字符串不可重复
public void testSort4() {
List<String> strList = new ArrayList<String>();
Random random = new Random();
String str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 10; i++) {
StringBuilder sb=new StringBuilder();
for(int j=0;j<random.nextInt(10);j++){
char char1 = str.charAt(random.nextInt(62));
sb.append(char1);
}
do{
for(int j=0;j<random.nextInt(10);j++){
char char1 = str.charAt(random.nextInt(62));
sb.append(char1);
}
}while(strList.contains(sb));
String st=sb.toString();
strList.add(st);
System.out.println("将要添加字符串:" + st);
}
System.out.println("-------------排序前--------------");
for (String string : strList) {
System.out.println("元素:" + string);
}
Collections.sort(strList);
System.out.println("----------------排序后-------------------");
for (String string : strList) {
System.out.println("元素:" + string);
}
}

1人推荐
随时随地看视频
慕课网APP