手记

Java入门第三季 6-5 Collections实现随机字符串排序

欢迎交流(⊙o⊙)…

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

public class CollectionsTest {

    public void test1(){
        List<String> list = new ArrayList<String>();
        Random rd = new Random();
        String str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder sb = null;
        String key = null;
        while(list.size()<10){
            do {
                sb = new StringBuilder();
                for (int j = 0; j < rd.nextInt(10); j++) {
                    String s = ""+str.charAt(rd.nextInt(str.length()));
                    if (sb.toString().contains(s)) { //保证字符不重复
                        j--;
                        continue;
                    }
                    sb.append(s);
                }
                key = sb.toString();
                sb=null;
            } while (key.isEmpty() || list.contains(key));//保证list元素不重复,不为空
            list.add(key);
        }
        System.out.println("=============排序前==============");
        for (String string : list) {
            System.out.println(string);
        }
        System.out.println("============排序后===============");
        Collections.sort(list);
        for (String string : list) {
            System.out.println(string);
        }       
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        CollectionsTest ct = new CollectionsTest();
        ct.test1();
    }
}
3人推荐
随时随地看视频
慕课网APP