package com.xxd.demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class StringSort {
// 创建Random对象
public static Random random = new Random();
public static void main(String[] args) {
// 创建List<String>
List<String> strs = new ArrayList<String>();
// 创建一个字符串,用于存储临时字符串
String str;
// 插入十条记录
for (int i = 0; i < 10; i++) {
// 生成一条随机的字符串
do {
str="";
for (int j = 0; j < random.nextInt(10); j++) {
str += generateChar();
}
} while (strs.contains(str));
strs.add(str);// 将字符串添加到列表中
}
System.out.println("--------------排序前------------------");
for (String string : strs) {
System.out.println("元素:" + string);
}
System.out.println("--------------排序后------------------");
Collections.sort(strs);
for (String string : strs) {
System.out.println("元素:" + string);
}
}
// 生成字符
public static char generateChar() {
int s = random.nextInt(3);
switch (s) {
case 0:
return (char) (48 + random.nextInt(10));
case 1:
return (char) (65 + random.nextInt(26));
case 2:
return (char) (97 + random.nextInt(26));
}
return 0;
}
}
打开App,阅读手记