private void testSort3() { final String chooseString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); List<String> stringList = new ArrayList<>(); int charNum; int stringLen; for (int j = 0; j<10; j++) { StringBuilder str = new StringBuilder(); stringLen = random.nextInt(10) + 1; // 本次字符串的长度 do { for (int i = 0; i<stringLen; i++){ charNum = random.nextInt(chooseString.length() - 1); // 随机获取一个字符 str.append(chooseString.charAt(charNum)); // 组成字符串 } } while (stringList.contains(str.toString())); stringList.add(str.toString()); } for (String s : stringList) { System.out.println(s); } System.out.println("-------------------- 排序后 ------------------------"); Collections.sort(stringList); for (String s : stringList) { System.out.println(s); } }
random.nextInt(chooseString.length() -
1
);nextInt(int)本来就是生成0-int之间的值不包括int的值,就相当于0-
chooseString.length() -
1,你将int的值设置为
chooseString.length() -
1其实是只能随机出0-
chooseString.length() - 2的值,所以你最后一个字符9不可能出现