手记

6-5 Collections.sort()的作业

package com.imooc.collection;

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

public class CollectionsTest {

public void testSort2() {
    List<String> list = new ArrayList<String>();
    Random random = new Random();
    //s是包含所有字符的字符串
    String s = "01234ABCmopqDEFGnKNO579PQRSTUVW6XYZabcdHIJefghijklrstLMwx8yz";

    //循环10遍(生成10个字符串)
    for(int i = 0; i < 10; i++) {
        String news = "";
        //设置一个10以内随机的整数
        int k = random.nextInt(10);
        //字符串长度为随机数k
        for(int j = 0; j < k; j++) {
            news += s.charAt(random.nextInt(s.length()));
        }
        list.add(news);
        System.out.println("添加对象:" + news);
    }
    System.out.println("---------排序前---------");
    for (String string : list) {
        System.out.println("元素:" + string);
    }
    Collections.sort(list);
    System.out.println("---------排序后---------");
    for (String string : list) {
        System.out.println("元素:" + string);
    }
}

public static void main(String[] args) {
    CollectionsTest ct = new CollectionsTest();
    ct.testSort2();

}

}

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