import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* 1. 创建List<String>之后,添加十条随机字符串
* 2. 每条字符串的长度为10以内的随机整数
* 3. 每个字符串的每个字符都随机生成
* 4. 字符可以重复,字符串不可重复
* @author Van0512
*
*/
public class SortRandomString {
private List<String> stringList;
private Random random;
private String data = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/*
* 构造器中初始化list和random
*/
public SortRandomString() {
this.stringList = new ArrayList<>();
this.random = new Random();
}
/*
* 返回一个字符数量在10以内的随机字符
*/
public String generateRandomString() {
StringBuilder sb = new StringBuilder();
//字符串长度1-10
int len = random.nextInt(10) + 1;
for(int i = 0; i < len; ++i) {
//随机选取字符的位置
int loc = random.nextInt(data.length());
sb.append(data.charAt(loc));
}
return sb.toString();
}
/*
* 往List中添加字符串
*/
public void addString2List(int n) {
for(int i = 0; i < n; ) {
String str = this.generateRandomString();
if(this.stringList.contains(str))
continue;
this.stringList.add(str);
++i;
}
}
/*
* 遍历
*/
public void traversal() {
for (String string : stringList) {
System.out.println(string);
}
}
public static void main(String[] args) {
SortRandomString srs = new SortRandomString();
srs.addString2List(10);
System.out.println("排序前");
srs.traversal();
Collections.sort(srs.stringList);
System.out.println("排序后");
srs.traversal();
}
}
打开App,阅读手记