手记

Java入门第三季6-5用Collections.sort()对泛型为String的List排序版本2

package 往List中随机添加字符串并排序;

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

public class ListRandomStringSortTest {
    public void sort(){
        List<String> stringList = new ArrayList<String>();
        Random random = new Random();
        String ch = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        for(int i = 0; i < 10; i++){
            StringBuilder sb = new StringBuilder();
            do{
                int stringLength = random.nextInt(10);
                for(int j = 0; j < stringLength; j++){
                    int number = random.nextInt(ch.length());
                    sb.append(ch.charAt(number));
                }
            }while(stringList.contains(sb.toString()));
            System.out.println("将要添加字符串:" + sb.toString() );
            stringList.add(sb.toString());
        }
        System.out.println("-----------排序前------------");
        for (String string : stringList) {
            System.out.println("元素:" + string);
        }
        System.out.println("-----------排序后------------");
        Collections.sort(stringList);
        for (String string : stringList) {
            System.out.println("元素:" + string);
        }
    }
    public static void main(String[] args) {
        ListRandomStringSortTest lrsst = new ListRandomStringSortTest();
        lrsst.sort();
    }

}

运行后符合以下要求:

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