package com.ppcc.sortDemo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
/**
* 随机产生一个长度在10以内的字符串,并进行排序
* @author ppcc
*
*/
public class sortDemo {
/**
* 字符数组,字符串元素从它里面获取
*/
private static final char[] strBase={
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9',
};
/**
* 字符串list长度
*/
private static int SIZE=10;
/**
* 随机字符串数组链表
*/
private ArrayList<String> randomStr;
/**
* 构造函数
*/
public sortDemo(){
//定义随机字符串数组链表
randomStr=new ArrayList<String>(SIZE);
//randomStr赋值
this.getStrList();
}
/**
* 随机产生一个长度在10以内的字符串
* @return 随机产生的字符串
*/
private String getOneStr(){
//定义可变的字符串
StringBuffer oneStr=new StringBuffer();
//定义随机数
Random random=new Random();
//字符串长度
int oneStrLen=(random.nextInt(9)+1);
//for循环产生一个长度在10以内的字符串
for(int i=0; i<oneStrLen; i++){
//随机产生下标
int index=random.nextInt(strBase.length);
//将随机获取的字符追加到字符串中
oneStr.append(strBase[index]);
}
return oneStr.toString();
}
/**
* 给randomStr赋值
*/
private void getStrList(){
//for循环在randomStr中添加是个字符串
for(int i=0; i<SIZE; i++){
//定义字符串
String str;
do{
//随机场所的字符串赋给str
str=getOneStr();
}while(randomStr.contains(str));
//直到原数组链表中不存该字符串,将其添加到randomStr
randomStr.add(str);
//添加成功提示语句
System.out.println("添加第"+(i+1)+"字符串:"+str);
}
}
/**
* 将字符串排序后比较前后区别
*/
public void sortRandomStr(){
System.out.println("******************排序前*********************");
for(String currStr : randomStr)
System.out.println("字符串:"+currStr);
//排序
Collections.sort(randomStr);
System.out.println("******************排序后*********************");
for(String currStr : randomStr)
System.out.println("字符串:"+currStr);
}
/**
* 主函数
* @param args
*/
public static void main(String[] args) {
(new sortDemo()).sortRandomStr();
}
}