手记

利用Collections.sort()对泛型为String的List排序

public void testSort2() {

    List<String> stringList = new ArrayList<String>();

    String base = "abcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();

    for (int j = 0; j < 10; j++) {

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < random.nextInt(10); i++) {
            do {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            } while (stringList.contains(sb));

        }

        stringList.add(sb.toString());
        System.out.println("随机生成的字符串为:" + sb);
    }
    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);
    }

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