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
点击查看更多内容
3人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦