手记

Collections.sort()对随机生成字符串排序

    /**
     * 随机生成十个长度不超过10的字符串,进行排序,没有重复
     */
    public void testSort3() {
        List<String> stringList = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            StringBuffer tempString = new StringBuffer();
            Character[] characters = {'0', 'a', 'A'};
            do {
                int k = (int) (Math.random() * 10);
                // System.out.println(k);
                for (int j = 0; j <= k; j++) {
                    int t = random.nextInt(3);
                    // System.out.println(t);
                    if (t == 0) {
                        tempString.append((char) (characters[t].charValue() + random.nextInt(10)));
                    } else {
                        tempString.append((char) (characters[t].charValue() + random.nextInt(26)));
                    }
                }
            } while (stringList.contains(String.valueOf(tempString)));
            stringList.add(String.valueOf(tempString));
        }

        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.testSort1();
//        ct.testSort2();
        ct.testSort3();
    }
1人推荐
随时随地看视频
慕课网APP