YGT_郁子
2018-08-15 14:55
package 学生选课;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
//练习
//对String泛型的List进行排序,创建String泛型的List,添加三个乱序的String元素,调用Collection.sort()方法排序2-2
public class Practice {
String allString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public void testSort() {
List<String> stringList = new ArrayList<String>();
Random random = new Random();
for(int i = 0; i < 10; i++) {
StringBuilder sbu = new StringBuilder();
int length = random.nextInt(10) + 1;
do {
for(int j = 0; j < length; j++) {
int number = random.nextInt(allString.length());
sbu.append(allString.charAt(number));
}
}while(stringList.contains(sbu.toString()));
stringList.add(sbu.toString());
System.out.println("成功添加元素:" + sbu);
}
System.out.println("--------排序前--------");
for (String s : stringList) {
System.out.println("元素:" + s);
}
Collections.sort(stringList);
System.out.println("--------排序后--------");
for (String s : stringList) {
System.out.println("元素:" + s);
}
}
public static void main(String[] args) {
Practice p = new Practice();
p.testSort();
}
}
其中 int number = random.nextInt(allString.length());
sbu.append(allString.charAt(number)); 只是取了字符串中一个字符
Java入门第三季
409792 学习 · 4340 问题
相似问题