FieldingLiu
2016-07-24 12:28:23浏览 2574
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTest {
/**
* 返回随机字符a-z,A-Z,0-9
*/
public char getRandomCharacter() {
Random random = new Random();
int number = random.nextInt(3);
char result = ' ';
//随机生成字符的类型
switch (number) {
case 0:
result = (char) ((int) (Math.random() * 26 + 65));
break;
case 1:
result = (char) ((int) (Math.random() * 26 + 97));
break;
case 2:
result = (char) ((int) (Math.random() * 10 + 48));
break;
default:
getRandomCharacter();
}
return result;
}
/**
* 1.创建完List<String>后,往其中添加10条随机字符串
* 2.每条字符串长度为10以内的整数
* 3.每条字符串的每个字符随机生成且可以重复
* 4.但是每条字符串都不相同
*/
public void testStringCollectionsSort2() {
List<String> stringList = new ArrayList<String>();
Random random = new Random();
//生成10条随机字符串
for (int i = 0; i < 10; i++) {
//每条字符串长度10以内
int length = random.nextInt(10);
//初始的字符串
String randomString = " ";
do {
//往初始字符串里添加字符
while (length > 0) {
randomString += getRandomCharacter();
length--;
}
} while (stringList.contains(randomString));
stringList.add(randomString);
}
System.out.println("-------排序前-------");
for (String string : stringList) {
System.out.println("随机字符串:" + string);
}
Collections.sort(stringList);
System.out.println("-------排序后-------");
for (String string : stringList) {
System.out.println("随机字符串:" + string);
}
}
public static void main(String[] args) {
CollectionsTest ct = new CollectionsTest();
//ct.testIntegerCollectionsSort();
//ct.testStringCollectionsSort1();
ct.testStringCollectionsSort2();
//System.out.println(ct.getRandomCharacter());
}
}