手记

随机生成10位以内随机字符串并且排序

package com.yy.demo;

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

public class CollectionSort {
    private List<String> ls;

    public CollectionSort(){
        ls=new ArrayList<String>();
    }

    public static void main(String[] args) {
        CollectionSort cs=new CollectionSort();

        System.out.println("--------排序前---------");
        cs.createList();
        cs.forEach();
        System.out.println("--------排序后---------");
        cs.listSort();
        cs.forEach();
    }

    public void listSort(){
        Collections.sort(ls);
    }

    public void forEach(){
        for (String string : ls) {
            System.out.println("字符串:"+string);
        }
    }
    public void createList(){
        Random random=new Random();
        for (int i = 0; i < 10; i++) {
            String tmp;
            do{
                tmp=getRandomString(random.nextInt(10));
            }while(ls.contains(tmp));
            ls.add(tmp);
        }
    }
    public String getRandomString(int length){
        String originString="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuffer sb=new StringBuffer();
        Random random=new Random();
        for (int i = 0; i < length; i++) {
            sb.append(originString.charAt(random.nextInt(originString.length())));
        }
        return sb.toString();
    }
}
0人推荐
随时随地看视频
慕课网APP