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();
}
}
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦