public void testSortString() {
List<String> stringList = new ArrayList<>();
/*随机生成10条字符串*/
String s;
for (int i = 0; i < 10; i++) {
do{
// s = randomString();/*字符串随机方法1*/
s = stringRandom();/*字符串随机方法2(推荐)*/
}while(stringList.contains(s));
stringList.add(s);
System.out.println("成功添加字符串:" + s);
}
System.out.println("-----------Before Sort------------");
for (String string : stringList) {
System.out.println("元素:" + string);
}
Collections.sort(stringList);
System.out.println("-----------After Sort------------");
for (String string : stringList) {
System.out.println("元素:" + string);
}
}
/*字符串随机方法1*/
public String randomString(){
Random random = new Random();
StringBuilder sb = new StringBuilder();
char[] A_a_0 = {'A','a','0'};
Integer charRadom; // 字符数组A_a_0下标
Integer stringLength;//字符串长度 1~10
Integer numRandom;//数字随机范围 0~9
Integer letterRandom;//字母随机范围 0~25
/*防止出现长度为0的情况*/
do {
stringLength = random.nextInt(10);
} while (stringLength == 0);
for (int i = 1; i <= stringLength; i++) {
char c;
/*字符数组A_a_0下标随机,0~2*/
charRadom = random.nextInt(3);
/*数字的情况*/
if (charRadom == 2) {
numRandom = random.nextInt(10);//数字随机范围 0~9
/*将 ‘0’ 的ASCII码值 加上 随机数,并强转为字符*/
c = (char) (A_a_0[charRadom] + numRandom);
sb.append(c);
}else{ // 字母的情况
letterRandom = random.nextInt(26);//字母随机范围 0~25
/*将 ‘a’ 或 'A' 的ASCII码值 加上 随机数,并强转为字符*/
c = (char) (A_a_0[charRadom] + letterRandom);
sb.append(c);
}
}
return sb.toString();
}
/*字符串随机方法2(推荐)*/
public String stringRandom() {
StringBuilder sb = new StringBuilder();
String s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] c = s.toCharArray();//将字符串转化为字符数组
Random random = new Random();
Integer length ;//字符串长度
Integer charRandom;//字符数组c下标随机
/*防止出现长度为0的情况*/
do {
length = random.nextInt(10);
} while (length == 0);
for (int i = 1; i <= length; i++) {
charRandom = random.nextInt(c.length);
sb.append(c[charRandom]);
}
return sb.toString();
}
public static void main(String[] args) {
CollectionsTest ct = new CollectionsTest();
ct.testSortString();
}
打开App,阅读手记
热门评论
厉害了sadasdasdasdasdsad