慕粉2001159793
2017-09-05 21:52:35浏览 2400
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTest {
public void testSort(){
List<String> stringsList = new ArrayList<String>();
Random random1 = new Random();
String f1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
//创建一个内容可变的字符串对象
StringBuilder f2 = new StringBuilder();
for(int i=0;i<10;i++){
do{
/*
* 这里用9+1是因为如果随机到0还可以加1,将0避免掉,不然0个字符串无法与其它字符比较
*/
int k = random1.nextInt(9)+1;
//如果新创建的随机字符串与之前的重复了,则清空该字符串,重新来过
f2 = new StringBuilder();
for(int j=0;j<k;j++){
//charAt(int index)获取字符串中指定位置的字符
f2.append(f1.charAt(random1.nextInt(f1.length())));
}
}while(stringsList.contains(f2.toString()));
System.out.println("将要添加字符串:'" + f2.toString() + "'");
stringsList.add(f2.toString());
}
System.out.println("---------------排序前--------------");
for (String string : stringsList) {
System.out.println("元素:" + string);
}
Collections.sort(stringsList);
System.out.println("---------------排序后--------------");
for (String string : stringsList) {
System.out.println("元素:" + string);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionsTest ct = new CollectionsTest();
ct.testSort();
}
}