package?com.kandy.imoockecheng.listmap;
import?java.util.ArrayList;
import?java.util.Collections;
import?java.util.List;
import?java.util.Random;
public?class?StringSort?{
????public?static?void?main(String[]?args)?{
????????/*
?????????*?隨機生成10條長度10以內,不可重復的字符串,每條字符串內的字符可以重復
?????????*?為節省String消耗,全部使用?StringBuilder
?????????*/
????????//定義字符串條數
????????int?count?=?10;
????????//定義最大字符串的長度
????????int?maxLength?=?10;
????????//定義備選字符N個
????????StringBuilder?stringBuilder?=?new?StringBuilder("ABCDEFGHIJGLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890");
????????//定義被選出來的字符串
????????StringBuilder?stringSel?=?new?StringBuilder();
????????//創建字符串List集合
????????List<String>?strList?=?new?ArrayList<>();
????????//do循環控制字符串的條數
????????do?{
????????????//隨機字符串的長度(10以內)
????????????int?rdLong?=?new?Random().nextInt(maxLength);
????????????//for循環隨機拼湊字符的和長度
????????????for?(int?i?=?0;?i?<?rdLong;?i++)?{
????????????????//隨機獲取備選字符串某個字符的索引位置
????????????????int?index?=?new?Random().nextInt(stringBuilder.length());
????????????????//按索引位置選出一個字符,把隨機生成的字符追加到stringSel
????????????????stringSel.append(stringBuilder.charAt(index));
????????????}
????????????//如果包含字符串,重新生成隨機字符串
????????????if(strList.contains(stringSel.toString()))?continue;
????????????//把隨機生成的字符串添加到strList中
????????????strList.add(stringSel.toString());
????????????//清空stringSel
????????????stringSel.delete(0,stringSel.length()-1);
????????}?while?(strList.size()?!=?count);?//10條后跳出do循環
????????System.out.println("*******排序前************");
????????strList.forEach(System.out::println);
????????//進行排序
????????Collections.sort(strList);
????????System.out.println("*******排序后************");
????????strList.forEach(System.out::println);
????}
}
2020-02-18
我覺得可能是Collection是一個父類的接口,List是它的子類接口,并沒有繼承sort方法
2020-01-04
運行結果: