package JavaSeason3.CollectionFramework;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* Created by Administrator on 2017/1/18.
*/
public class CollectionsTest {
/**
* 对int型List排序
*/
public void testSort1(){
List<Integer> integerList = new ArrayList<>();
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("------------------排序前-----------------");
for (Integer integer : integerList) {
System.out.println("元素:" + integer);
}
Collections.sort(integerList);
System.out.println("------------------排序后-----------------");
for (Integer integer : integerList) {
System.out.println("元素:" + integer);
}
}
/**
* 对String泛型的List进行排序
*/
public void testSort2(){
List<String> stringList = new ArrayList<>();
// stringList.add("microsoft");
// stringList.add("google");
// stringList.add("lenovo");
Random random = new Random();
String s;
for (int i = 0; i < 10; i++) {
do {
int length = random.nextInt(10);
s = getRandomString(length);
}while (stringList.contains(s));
stringList.add(s);
}
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 String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i < length; ++i){
int number = random.nextInt(62);//[0,62)
sb.append(str.charAt(number));
}
return sb.toString();
}
public static void main(String[] args) {
CollectionsTest ct = new CollectionsTest();
// ct.testSort1();
ct.testSort2();
}
}
------------------排序前-----------------
元素:jeB
元素:4R
元素:waHX8v7li
元素:w
元素:FhJLBA
元素:J
元素:VNapr
元素:1d3EdvS
元素:obFmdjHi
元素:iyi8QG41
------------------排序后-----------------
元素:1d3EdvS
元素:4R
元素:FhJLBA
元素:J
元素:VNapr
元素:iyi8QG41
元素:jeB
元素:obFmdjHi
元素:w
元素:waHX8v7li
Process finished with exit code 0