代码如下
package testCollections;
import java.util.Random;
public class Initail {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sort st = new Sort();
Random random = new Random();
int i = 0;
//一共添加10次.
do{
String b=st.newString();
if(st.addString(b)){
i++;
}else{
continue;
};
}while(i<10);
//打印排序前.
System.out.println("----------排序前-----------");
st.put();
//打印排序后.
System.out.println("----------排序后-----------");
st.testSort();
st.put();
}
}
package testCollections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Sort {
public List<String> a ;
public Sort(){
this.a= new ArrayList<String>();
}
//生成一个新的字符串
public String newString(){
String b = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
Random random = new Random();
String newString = "" ;
//从字符串b中挑选少于10个字符组成新的字符串.
for(int j = 0;j<=random.nextInt(10);j++){
int c=random.nextInt(b.length());
char cr = b.charAt(c);
newString = newString + cr;
}
System.out.println("生成的字符串为:"+newString);
return newString;
}
public boolean addString(String newString){
//判断List中是否有新生成的字符串,没有则添加到List中,且返回一个boolean型的值用作判断.
if(!(a.contains(newString))){
a.add(newString);
return true;
}else{
return false;
}
}
//遍历List
public void put(){
for (String string : a) {
System.out.println("元素:"+string);
}
}
//排序.
public void testSort(){
Collections.sort(a);
}
}