参考了其他同学的思路,简化了一下自己的算法,源文件为Test.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Test03 {
private static List<String> stringList;
private static String finalString;
public static void main(String[] args) {
stringList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
do {
createString();
} while (stringList.contains(finalString));
stringList.add(finalString);
}
System.out.println("————————————————————————排序前——————————————————————————");
listOut(stringList);
Collections.sort(stringList);
System.out.println("————————————————————————排序后——————————————————————————");
listOut(stringList);
}
private static void createString() {
Random random = new Random();
StringBuffer sb = new StringBuffer();
int length = random.nextInt(10)+1;
for (int i = 0; i < length; i++) {
//以下为Test02.java的改进之处
String raw = "123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
sb.append(raw.charAt(random.nextInt(raw.length())));
}
finalString = sb.toString();
}
private static void listOut(List<String> stringList) {
for (String string : stringList) {
System.out.println("元素:"+string);
}
}
}