五竹
2015-06-19 14:57
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* 创建一个String泛型的List,往其中添加十条随机字符串,排序后打印输出
* 每条字符串的长度为10以内的随机整数
* 每条字符串的每个字符都为随机生成的字符,字符可以重复
* 每条随机字符串不可重复
*/
public class CollectionsSortExercise {
/**
* 获取一个随机字符串,字符串长度为10以内的随机整数
*/
public static String getRandomString(int length) {
// 定义一个基字符串base,用于从其中生成随机字符串
String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder();
Random random = new Random();
// 定义一个字符串长度的变量finalLength,其值为[1,10]间的随机值
int finalLength = random.nextInt(length) + 1;
// 生成一个字符串对象sb
for (int i = 0; i < finalLength; i++) {
int index = random.nextInt(base.length());
sb.append(base.charAt(index));
}
return sb.toString();
}
/**
* 创建一个String泛型的List,往其中添加获取的十条随机字符串,排序后打印输出
*/
public void testSort() {
List<String> stringList = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
String string;
do {
string = getRandomString(10);
} while (stringList.contains(string));
stringList.add(string);
System.out.println("成功添加一条随机字符串:" + string);
}
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) {
// TODO Auto-generated method stub
CollectionsSortExercise cse = new CollectionsSortExercise();
cse.testSort();
}
}
知道了,谢谢
楼主,求指点!
我认为应该把你的代码int finalLength = random.nextInt(length) + 1; 改为int finalLength = random.nextInt(10) + 1;把传进来的int length删掉,还有把testSort()方法中的代码string = getRandomString(10);中的10去掉。
这样做会不会好点。。。。还有我不懂这两种的区别?求指点!谢谢!
感谢楼主分享!
Java入门第三季
409775 学习 · 4546 问题
相似问题