import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTest {
public void testSort3() {
StringBuilder st = new StringBuilder();//构建StringBuilder类
List<String> stringlist = new ArrayList<String>();
String str = "0123456789abcdefghijklmnobqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 10; i++) {//10条字符串
Random random = new Random();
do {
for (int j = 0; j < random.nextInt(9) + 1; j++) {//建立10长度以内的字符串
int k = random.nextInt(61);
st.append(str.charAt(k));
}
//防止字符串重复,并且把st转化为String类,使其满足泛型,被contains方法调用
} while (stringlist.contains(st.toString()));
stringlist.add(st.toString());
st = new StringBuilder();//重新构造st,防止其接着加字符,起到让st字符串"清零"的作用
}
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.testSort3();
}
打开App,阅读手记