package sss;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class collectionstest {
public void sorttext3(){
List<String> a = new ArrayList<String>();
//String[] b = new String[10];
String st = "abcdefghijklmnopqrstuvwxyz"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "0123456789";
Random c = new Random(10);
int i=0;
StringBuffer sb = new StringBuffer();
for(int z=0;z<10;z++){
do{
int j=c.nextInt();
for(;i<j;i++){
Random d = new Random(62);
int num = d.nextInt();
sb.append(st.charAt(num));
}
}while(a.contains(sb.toString()));
a.add(sb.toString());
}
System.out.println("···········排序前");
for (String string : a) {
System.out.println("元素"+a);
}
Collections.sort(a);
System.out.println("``````````排序后");
for (String string : a) {
System.out.println("元素 "+a);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
collectionstest a = new collectionstest();
// a.testsort1();
// a.sortText2();
a.sorttext3();
}
}
Random num=new Ramdom(62);这条语句是可以出现62的,但是你的String st 的范围为0~61,所以会出现越界,
另外你的foreach语句遍历a,为什么不System.out.println(string);而要输出a那?
random(i)取的数不是0-(i-1么?
public void sorttext3(){
List<String> a = new ArrayList<String>();
//String[] b = new String[10];
String st = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random c = new Random();
for(int z=0;z<10;z++){
StringBuffer sb = new StringBuffer();
do{
int j=c.nextInt(10)+1;
for(int i=0;i<j;i++){
//Random d = new Random(62);
int num = c.nextInt(st.length());
sb.append(st.charAt(num));
}
}while(a.contains(sb.toString()));
a.add(sb.toString());
}
把你的StringBuffer 对象放到了for循环里了 ,要不每次循环,都会把之前循环过了字符串加里面,还有就是数组越界,不清楚怎么回事,不过改的代码,是没问题的!
你定义的st,直接把所有的元素写在一起,应该就好了。