前端老司机玩的Java练习题6-5答案,求关注及评论!!!
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class SortTest {
public List<String> listStr;
public Random random;
public SortTest() { l
istStr = new ArrayList<String>();
random = new Random();
}
//创建随机字符串
public void createListStr() {
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int len = str.length();
// 添加10个随机字符串
for (int i = 0; i < 10; i++) {
int itemLen = random.nextInt(6) + 5; // 5-10包括5和10
int start, end;
String resStr = "";
// 生产长度为5-10的随机字符串
for (int k = 0; k < itemLen; k++) {
String item;
do {
start = random.nextInt(len - 1);
end = start + 1;
item = str.substring(start, end);
} while (resStr.indexOf(item) > -1);
resStr += item;
}
listStr.add(resStr);
}
}
//字符串排序
public void shortListStr() {
Collections.sort(listStr);
}
public static void main(String[] args) {
SortTest st = new SortTest();
st.createListStr();
st.shortListStr();
System.out.println(st.listStr.toString());
}
}输出结果:
[508U4jw, CApkURXuYv, CtQ7i8, CuazfBHO, KN17Aac, MwJ9Ra, blqTcd, hNgt4J8oBi, hoBvzrdW, kcbPj]