手记

Java入门第三季 6-5 随机字符串

import java.util.*;

public class CollectionTest {
public void testSort(){
List <String> stringList= new ArrayList<String>();
String k;
for (int i=0;i<10;i++){
do{
k=randomString(10);
}
while(stringList.contains(k));
stringList.add(k);
}
System.out.println("------before sort--------");
for(String string: stringList){
System.out.println("element : " + string);
}
Collections.sort(stringList);
System.out.println("------After sort--------");
for(String string: stringList){
System.out.println("element : " + string);
}

}

public String randomString(int n) {
    Random random = new Random();
    String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    StringBuilder builder = new StringBuilder(); 
    for(int i = 0; i < n; i++)  builder.append(base.charAt(random.nextInt(base.length())));
    System.out.println("生成字符串:" + builder.toString());
    return builder.toString();
    }
public static void main(String[] args) {
    CollectionTest ct = new CollectionTest();
    ct.testSort();
    // TODO 自动生成的方法存根

}

}

1人推荐
随时随地看视频
慕课网APP