手记

利用Collections.Sort方法对泛型为String的List进行排序

package Test;

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

public class SortTest {
    public static void main(String[] args) {
        List<String> StringList = new ArrayList<String>();
        Random random = new Random();
        String s = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder sb = new StringBuilder();
        //添加十行记录
        for(int i = 1; i <= 10; i++){
            //获取每一行字符串的长度
            int length = random.nextInt(10);

            //随机生成字符串文字
            for(int j = 1; j <= length; j++){
                int sCharAt = random.nextInt(s.length());
                sb.append(s.charAt(sCharAt));
            }

            //添加生成的字符串
            StringList.add(sb.toString());

            //清空StringBuilder
            sb.delete(0, sb.length() - 1);
        }

        System.out.println("----------排序前--------");
        for(String st: StringList){
            System.out.println(st);
        }

        Collections.sort(StringList);
        System.out.println("----------排序后--------");
        for(String st: StringList){
            System.out.println(st);
        }
    }
}
1人推荐
随时随地看视频
慕课网APP