hua落人断唱
2016-06-21 16:55:08浏览 2823
import java.util.*;
public class Test {
public static void main(String[] args) {
Test test = new Test();
List<String> string = test.randomString(12, 10);//随机字符串的长度(12)和个数(10)
System.out.println("----------排序前-----------");
System.out.println("生成的10个随机字符串为:");
for (String str : string) {
System.out.println(str);
}
Collections.sort(string);
System.out.println("----------排序后-----------");
for (String str : string) {
System.out.println(str);
}
}
/*
*length:生成的随机字符串的长度,times:生成的随机字符串的个数
*/
public List<String> randomString(int length,int times){
List<String> string = new ArrayList<String>();
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < times; i++) {
for (int j = 0; j < length; j++) {
int number = random.nextInt(62);
strBuf.append(str.charAt(number));//重新给strBuf定义,防止它一直在后面append
}
if(!string.contains(strBuf)){
string.add(strBuf.toString());
strBuf = new StringBuffer();
}else{
i--;
}
}
return string;
}
}