011001100110
2018-01-20 12:30:25浏览 2071
/***
* 利用Collections.sort()方法对泛型为String的List进行排序
* 1.创建List<String>之后,往其中添加十条随机字符串
* 2.每条字符串的长度为10以内的随机整数
* 3.每条字符串的每个字符都为随机生成的字符,字符可以重复
* 4.每条随机字符串不可重复
*/
public void testSort3() {
List<String> strList = new ArrayList<>();
String str;
for(int i=0; i<10; i++) {
do {
str = addString();
}while(strList.contains(str));
strList.add(str);
System.out.println("成功添加了字符串:"+str);
}
System.out.println("----------------------排序前-----------------------");
int index = 1;
for (String string : strList) {
System.out.println("第"+(index++)+"个字符串:"+string);
}
Collections.sort(strList);
index = 1;
System.out.println("----------------------排序后-----------------------");
for (String string : strList) {
System.out.println("第"+(index++)+"个字符串:"+string);
}
}
public String addString() {
String seed = "QWERTYUIOPASDFGHJKLZXCVBNM0147258369qwertyuiopasdfghjklzxcvbnm";
StringBuilder sb = new StringBuilder();
Random random = new Random();
int length = random.nextInt(10)+1;//生成字符串长度
for(int i=0; i<length; i++) {
int index = random.nextInt(seed.length()); //生成索引位置
sb.append(seed.charAt(index));
}
return sb.toString();
}