package com.imooc.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class exerciseTest {
/**
- 利用Collections.sort()方法对泛型为stringList进行排序版本2
- 1.创建list<String>之后,往其中随机添加10条随机字符串;
- 2.每条字符串的长度为10以内的随机整数;
- 3.每条字符串的每个字符都为随机生成的字符,字符可以重复
- 4.每条随机字符串不可重复
*/
public String RandomString(int length) {
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuilder str1 = new StringBuilder();
for (int i = 0; i < length; i++) {
int num = random.nextInt(62);
str1.append(str.charAt(num));
}
return str1.toString();
}
public void randomStringSort() {
List<String> strList = new ArrayList<String>();
Random random = new Random();
String string;
//这里是要生成10个随机字符串,并且每个字符串长度为10以内的随机正整数
for (int i = 0; i < 10; i++) {
int k=random.nextInt(10);
do {
string = RandomString(k);
} while (k<1&&strList.contains(string));//判断不能包含相同的字符串,以及字符长度不能为0和负数
strList.add(string);
System.out.println("将要添加字符串:" + string );
}
System.out.println("--------------排序前----------------");
for (String string1 : strList) {
System.out.println("元素:" + string1);
}
Collections.sort(strList);
System.out.println("---------------排序后---------------");
for (String string1 : strList){
System.out.println("元素:" + string1);
}
}
public static void main(String[] args){
exerciseTest test = new exerciseTest();
test.randomStringSort();
}
}