/**
* 利用Collection.sort()方法对泛型String排序
* list中添加10个长度为10以内整数的随机String
*/
public void stringListTest(){
List<String> stringList = new ArrayList<String>();
Random random = new Random();
int num;
System.out.println("-----未排序前------");
for(int i = 0;i < 10;i++){
num = random.nextInt(10);
String string = createRandomString(num);
stringList.add(string);
System.out.println(string);
}
Collections.sort(stringList);
System.out.println("-----排序后------");
for(String string:stringList){
System.out.println(string);
}
}
/**
* 创建指定长度的字符串
* @param length
* @return String
*/
private String createRandomString(int length){
if(length == 0){
return "zero";
}
String baseStr = "abcdefghijklmnopqrstuzwxyz1234567890AB" +
"CDEFGHIGKLMNOPQRSTUZWXYZ!@#$%^&*()_+";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0;i<length;i++){
int num = random.nextInt(baseStr.length());
sb.append(baseStr.charAt(num));
}
return sb.toString();//将StringBuffer类转换成String类并返回
}
public static void main(String[] args){
CollectionsTest ct = new CollectionsTest();
ct.stringListTest();
}