public class CollectionsTest {
/**
* 生成一定长度的随机字符串, 并返回.
*
* @param length 字符串长度
* @return
*/
public String generatorRandomString(int length) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuilder result = new StringBuilder();
// 生成
for (int i = 0; i < length; i++) {
int l = random.nextInt(chars.length());
result.append(chars.charAt(l));
}
return result.toString();
}
/**
* 对随机字符串进行排序
*/
public void testSortRandomString() {
List<String> strings = new ArrayList<String>();
String str = null;
for (int i = 0; i < 20; i++) {
do {
str = generatorRandomString(5);
}
// 如果序列中含有该字符串, 那就再生成一次, 直到序列中没有该字符串为止.
while (strings.contains(str));
strings.add(str);
System.out.println("添加元素: " + str);
}
System.out.println("------排序前------");
for (String s : strings) {
System.out.print(s + ", ");
}
System.out.println();
System.out.println("------排序后------");
Collections.sort(strings);
for (String s : strings) {
System.out.print(s + ", ");
}
}
public static void main(String[] args) {
CollectionsTest test = new CollectionsTest();
test.testSortRandomString();
}
}
打印结果:
添加元素: HJ9FC
添加元素: aLEIv
添加元素: Dlxzm
添加元素: NrOh4
添加元素: GGoHJ
添加元素: 6Yhk5
添加元素: jYPgs
添加元素: 2kMvH
添加元素: ngoEN
添加元素: fRCTO
添加元素: 8l5Zx
添加元素: VYyl4
添加元素: lSb52
添加元素: qd3f8
添加元素: RgPGn
添加元素: NOuFK
添加元素: Y1Dfb
添加元素: cayRB
添加元素: WuQT0
添加元素: w2MAO
------排序前------
HJ9FC, aLEIv, Dlxzm, NrOh4, GGoHJ, 6Yhk5, jYPgs, 2kMvH, ngoEN, fRCTO, 8l5Zx, VYyl4, lSb52, qd3f8, RgPGn, NOuFK, Y1Dfb, cayRB, WuQT0, w2MAO,
------排序后------
2kMvH, 6Yhk5, 8l5Zx, Dlxzm, GGoHJ, HJ9FC, NOuFK, NrOh4, RgPGn, VYyl4, WuQT0, Y1Dfb, aLEIv, cayRB, fRCTO, jYPgs, lSb52, ngoEN, qd3f8, w2MAO,
Process finished with exit code 0