l15047063
2017-01-11 18:16:18浏览 2295
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTest {
/**
* 利用Collections.sort()方法对泛型为String的List进行排序版本2:
* 1.创建完List<String>之后,在其中添加十条随机字符串;
* 2.每条字符串的长度为10以内的随机整数;
* 3.每条字符串的每个字符都为随机生成的字符,字符可以重复;
* 4.每条随机字符串不可重复。
*/
public void testSort2_2(){
List<String> stringList = new ArrayList<String>();
Random random = new Random();
StringBuilder strb = null;
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 10; i++) {
do {
int n = random.nextInt(10);
strb = new StringBuilder(n);
for (int j = 0; j < n+1; j++) {
char c = str.charAt(random.nextInt(str.length()));
strb.append(c);
}
} while (stringList.contains(strb));
stringList.add(strb.toString());
}
System.out.println("---------排序前---------");
for (String string : stringList) {
System.out.println("元素:" + string);
}
Collections.sort(stringList);
System.out.println("---------排序后---------");
for (String string : stringList) {
System.out.println("元素:" + string);
}
}
public static void main(String[] args) {
CollectionsTest ct = new CollectionsTest();
ct.testSort2_2();
}
}