我不孤单
2017-06-20 21:47:48浏览 4640
package ImoocTest;
import java.util.*;
import java.util.ArrayList;
/**
* 随机生成10个长度10以内的字符串添加进List集合
* 输出排序前集合元素
*用Collections.sort(list)排序后再次输出,对比两次结果
*/
public class CollectionsTest {
public static List<String> slist = new ArrayList<String>();
/**
* 随机生成字符串 参数为字符串长度
*
*/
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 遍历显示集合
*/
public void listShow() {
for (String string : slist) {
System.out.println(string);
}
}
/**
* 调用getRandomString()方法生成长度随机10以内的字符串10个 将字符串保存进List集合中
*
*/
public void stringListTest() {
String aString;
for (int i = 0; i < 10; i++) {
do {
Random random = new Random();
int length = random.nextInt(9)+1;
// 上面语句字符串长度为1-10,下面语句为0到10,可能出现空字符串
//int length = random.nextInt(10);
aString = getRandomString(length);
} while (slist.contains(aString));
slist.add(aString);
}
}
public static void main(String[] args) {
CollectionsTest cTest = new CollectionsTest();
cTest.stringListTest();
System.out.println("排序前数组元素");
cTest.listShow();
Collections.sort(slist);
System.out.println("排序后数组元素");
cTest.listShow();
}
}