美文网首页
JAVA练习:对10个随机生成的字符串排序

JAVA练习:对10个随机生成的字符串排序

作者: 虫yu | 来源:发表于2018-11-15 16:06 被阅读7次
    package com.collection;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Random;
    
    public class CollectionsTest {
    
        /**
         * 1、在List<String>中添加10条随机字符串
         * 2、每条字符串的长度为10以内的随机整数
         * 3、每条字符串的每个字符都为随机生成的字符,字符可以重复
         * 4、每条随机字符串不可重复
         */
        public void testSort() {
            List<String> stringList = new ArrayList<String>();
            Random random = new Random();
            // 62个数
            String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
            
            // 外围一个循环是10
            for(int i = 0; i < 10 ; i++) {
                // random.nextInt(int n) 返回的是[0, n) =>[0, n-1]
                // 这里需要的是[1, 10]
                //[0, 10) + 1 => [1, 11) => [1, 10]
                int stringLength = random.nextInt(10) + 1;
                StringBuilder tempSB;
                
                do {
                    // 新生成一个旧的由系统回收
                    tempSB = new StringBuilder();
                    // 内层是随机长度
                    for(int j = 0; j < stringLength ; j++) {
                        int charIndex = random.nextInt(str.length());
                        char tempChar = str.charAt(charIndex);
                        tempSB.append(tempChar);
                    }
                    // 如果tempSB.toString()与stringList中已有的元素相同,重新生成随机字符串
                } while(stringList.contains(tempSB.toString()));
                 
                stringList.add(tempSB.toString());
            }
     
            System.out.println("-------------排序前--------------");
            for (String string : stringList) {
                System.out.println("元素:" + string);
            }
     
            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.testSort();
        }
    
    }
    

    参考资料:

    java生成随机字符串的两种方法

    相关文章

      网友评论

          本文标题:JAVA练习:对10个随机生成的字符串排序

          本文链接:https://www.haomeiwen.com/subject/usbyfqtx.html