我也发一发
package randomcharacter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class RandomCharacter {
public void randomChar() {
//创建一个数组
List<String> stringList = new ArrayList<String>();
//创建一个random对象
Random random = new Random();
//创建10条字符串
for(int i=0;i<10;i++) {
//创建一个字符串
String str = "";
do {
//创建字符串长度(小于10的随机数字)
int strLength = random.nextInt(10);
for(int j=0;j<=strLength;j++) {
//每次随机生成一个字符
int randomNum = random.nextInt(62);
char tempChar;
if(randomNum<10) {
tempChar = (char)(randomNum + 48);
}else if(randomNum>=10 && randomNum<36) {
tempChar = (char)(randomNum + 55);
}else {
tempChar = (char)(randomNum + 61);
}
str = str + tempChar;
}
}while(stringList.contains(str));
stringList.add(str);
System.out.println("成功添加第"+(i+1)+"个字符串:"+str);
}
System.out.println("----------------排序前----------------");
int beforeSortingNum=1;
for(String string:stringList) {
System.out.println("第"+(beforeSortingNum++)+"个元素:"+string);
}
Collections.sort(stringList);
System.out.println("----------------排序后----------------");
int afterSortingNum=1;
for(String string:stringList) {
System.out.println("第"+(afterSortingNum++)+"个元素:"+string);
}
}
}
=============================================================================
package randomcharacter;
public class Test {
public static void main(String[] args) {
RandomCharacter rc = new RandomCharacter();
rc.randomChar();
}
}