手记

应用 Collections.sort() 实现 List 排序 练习

package com.imooc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionSort {

public void testSort(){
    List<String> stringList=new ArrayList<String>();
    //讲需要的字符存入字符串originString,供后面提取
    String originString="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    Random random =new Random();

    //生成10条字符串
    for (int i = 0; i<10;i++){
        //初始化字符串st
        String st="";
        //每条字符串 长度为10以内
        int length=random.nextInt(9)+1;
        //为字符串添加字符
        for(;length>0;length--){
            //从orginString中随机提取字符
            int n =random.nextInt(62);
            char m=originString.charAt(n);
            //添加字符串
            st += m;
        }
        while(stringList.contains(st));
            stringList.add(st);

    } 
        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){
    CollectionSort cs=new CollectionSort();
    cs.testSort();

}

}

1人推荐
随时随地看视频
慕课网APP