package project_collection_map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTest {
/**
* 通过Collections.sort()方法排序
*/
public void testSort(){
List<Integer> integerList = new ArrayList<Integer>();
//插入十个100以内的不重复随机整数
Random random = new Random();
Integer k;
for (int i = 0; i < 10; i++){
do{
k = random.nextInt(100);
} while (integerList.contains(k));
integerList.add(k);
System.out.println("成功添加整数:" + k);
}
System.out.println("..........排序前............");
for (Integer integer:integerList){
System.out.println("元素:" + integer);
}
System.out.println("...........排序后................");
Collections.sort(integerList);
for (Integer integer:integerList){
System.out.println("元素:" + integer);
}
}
/**
* 对String泛型的List进行排序
*/
public void testSort1(){
List<String> stringList = new ArrayList<String>();
stringList.add("shuxue");
stringList.add("yuwen");
stringList.add("yingyu");
System.out.println("..............排序前...............");
for(String str:stringList){
System.out.println("元素:" + str);
}
Collections.sort(stringList);
System.out.println("..............排序后...............");
for(String str:stringList){
System.out.println("元素:" + str);
}
}
public void testSort2(){
List<String> strList = new ArrayList<String>();
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//生成随机数
Random random = new Random();
for (int p = 0; p < 10; p++) {
StringBuffer sb = new StringBuffer();
// String sb = "";
for (int j = 0; j < random.nextInt(9)+1; j++) {
sb.append(str.charAt(random.nextInt(str.length())));
// sb+=str.charAt(random.nextInt(str.length()));
}
String q = sb.toString();
System.out.println("成功添加字符串:"+q);
strList.add(q);
}
System.out.println("..............排序前...............");
for(String s:strList){
System.out.println("元素:" + s);
}
Collections.sort(strList);
System.out.println("..............排序后...............");
for(String s:strList){
System.out.println("元素:" + s);
}
}
public static void main(String[] args) {
CollectionsTest ct = new CollectionsTest();
// ct.testSort();
// ct.testSort1();
ct.testSort2();
}
}
打开App,阅读手记