public void test2(){ List<String> StringList=new ArrayList<String>(); Random random=new Random(); char [] charArray=("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); for(int j=0;j<10;j++){ StringBuilder sb=new StringBuilder(); do{ for(int i=0;i<random.nextInt(10)+1;i++){ sb.append(charArray[random.nextInt(62)]); } StringList.add(sb.toString()); } while(StringList.contains(sb.toString())); } System.out.println("*********排序前*********"); for (String string : StringList) { System.out.println(string); } System.out.println("********排序后***********"); Collections.sort(StringList); for (String string : StringList) { System.out.println(string); } }
12行不对,应该放到14行的后面
内层for循环好像不对。。看看我写的吧
public class RandomStr {
public List<String> list = new ArrayList<String>();
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
public static void main(String[] args) {
RandomStr rm = new RandomStr();
rm.sortStr(rm.addStr());
}
//生成字符串集合
List<String> addStr(){
for(int i=0;i<10;i++){
StringBuilder sb = new StringBuilder();
int tmp = 0;
char ch;
do{
tmp = random.nextInt(10);
}while(tmp==0);
for(int j=0;j<tmp;j++){
do{
ch = str.charAt(random.nextInt(str.length()));
}while(list.contains(sb));
sb.append(ch);
}
list.add(sb.toString());
}
return list;
}
//排序字符串集合
void sortStr(List<String> list){
System.out.println("=====排序前的顺序=====");
for(String str:list){
System.out.print(str+"-");
}
Collections.sort(list);
System.out.println();
System.out.println("=====排序后的顺序=====");
for(String str:list){
System.out.print(str+"-");
}
}
}
你这个do...while的程序,当集合里面含有某个相等的字符串的时候才会往集合加入字符串对象,你看看是不是?
你还是先看看do...while语句吧,这个程序的执行过程你还没有弄明白