手记

Java第三季 Collections.sort()实现包含随机长度字符串的List排序

CollectionsTest.Java

package com.collection;

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

public class CollectionsTest {

    /**
     * 生成10条1-9长度之间的随机字符串,并使用sort()方法排序
     */
    public void testSort3(){
        List<String> stringList = new ArrayList<String>();
        for(int i=0;i<10;i++){
            StringBuffer sb = new StringBuffer();
            do{
                //(A-Z,a-z,0-9)字符串
                String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
                Random random = new Random();
                //每次生成随机长度(1-9)
                int length = random.nextInt(9)+1;
                for(int j=0;j<length;j++){
                    int number = random.nextInt(62);
                    //每次取索引位置为随机数字(0-61)的字符,一共取length次
                    sb.append(str.charAt(number));
                }
            }while(stringList.contains(sb.toString()));//避免字符串重复
            stringList.add(sb.toString());
            System.out.println("成功添加字符串:"+sb.toString());
        }
        System.out.println("--------------------排序前--------------------");
        for (String string : stringList) {
            System.out.println("元素:"+string);
        }
        //排序10条字符串
        Collections.sort(stringList);
        System.out.println("--------------------排序后--------------------");
        for (String string : stringList) {
            System.out.println("元素:"+string);
        }   
    }

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

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